I have a class with a dict attribute, like this :
class MyClass:
def __init__(self):
self.mydict = {'var1': 'value1', 'var2': 'value2', ...}
When I want to get the values, I have to do this :
cls = MyClass()
print(cls.mydict['var1'])
print(cls.mydict['var2'])
What is the solution to get the values directly in attributes please :
cls = MyClass()
print(cls.var1)
print(cls.var2)
You can directly update the
__dict__
attribute of your object I believe:You could add an additional function to the class that will be able to parse the dict and insert the relevant attributes:
I'm using the built-in
setattr()
function here to set attributes with dynamic names/values:You can call this function inside your constructor after the
mydict
variable is defined or even just place the loop in the constructor.Using
setattr
, you can set attribute dynamically:Another way would be to override
__getattr__
and__setattr__
together, which avoids having two object references to the same attribute in the class instance object (one O.R. tovalue1
insidemyobj.mydict['var1']
, and another O.R. tovalue1
inmyobj.__dict__['var1']
):Note that doing it this way means you cannot add more key,value pairs to
mydict
unless you call the property directly, e.g.:Also note that getting and deleting the
mydict
members will be overridden by any existing attribute of the same name (not only that, but you can't deletemydict
members at all unless you also override__delattr__
to enable this behavior):If you want to change this behavior, you have to override
__getattribute__
(EDIT: which, as bruno desthuilliers notes below, is usually not a good idea).Another solution is to implement
__getattr__
: