This question already has an answer here:
For example in pseudocode:
class Example:
def __init__(self, dict):
for key, value in dict.items():
self.key = value
a = Example({"objectVariable": ["some", "data"]})
print(a.objectVariable)
>>>["some", "data"]
How would I implement this?
Thanks in advance
Assign dict
to the built in __dict__
for greater simplicy:
class Example:
def __init__(self, dict):
self.__dict__ = dict
self.__dict__.update(dict)
should be preferred as it is more generally applicable. Also, later changes to the passed dict
will not be reflected in the instance attributes! - schwobaseggldict
would also be nice. - schwobaseggl
You're looking for __getattr__
, which will be called if the slot doesn't exist.
class Example:
def __init__(self, dict):
self.dict = dict
def __getattr__(self, prop):
return self.dict[prop]
setattr(self, key, value)
. - ekhumoro