John
John

Reputation: 31

Naming a class' self a variable name

Is it possible to use the name of an input, eg a yaml/dict key, on self while not knowing that key literally?

Meaning, if there were some data like:

entries = [
    {'foo': 'foo 1', 'bar': 'bar 1'},
    {'foo': 'foo 2', 'bar': 'bar 2'},
]

How could we do the below without explicitly preprogramming 'foo' and 'bar' to name the self variables?

class entry(object):
    def __init__(self):
        self.foo = entries[0]['foo']
        self.bar = entries[0]['bar']

And I suppose those self assignments would not have to be named foo and bar, but at least be able to reference them as such.

Upvotes: 2

Views: 1074

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32294

You can use the built-in function setattr to add/set an attribute on an object in Python

def __init__(self):
    for k, v in entries[0].items():
        setattr(self, k, v)

Upvotes: 5

Related Questions