Reputation: 76
I have a class that contains a dictionary, i use __getattr__(key)
to get nicer access to the dictionary[key]
now i would like to be able to set things in the dictionary with the same access style.
Class foo(object):
def __init__(self, name):
self.props = {"name":name}
def __getattr__(self, attribute):
return self.props[attribute]
This is so i can access it in this way
f = foo("test")
print f.name
I would like the ability to set the attributes aswell, however using setattr is proving problematic due to it being called before anything else fails. Is there a way to make it act like getattr?
Upvotes: 1
Views: 85
Reputation: 31643
__setattr__
is fine, but you need to protect yourself from case when __setattr__
is called before self.props
is set (RuntimeError: maximum recursion depth exceeded
)
class foo(object):
# List of properties which are not stored in the props dict
__slots__ = ('props', 'other_property')
def __init__(self, name):
self.props = {"name":name}
self.other_property = 2
def __getattr__(self, attribute):
return self.props[attribute]
def __setattr__(self, name, value):
if name in self.__slots__:
super(foo, self).__setattr__(name, value)
else:
self.props[name] = value
f = foo("name")
print f.name
f.value = 2
f.name = "TEST"
print f.value
print f.props
Upvotes: 1