I had to write a class of some sort that overrides __getattribute__
.
basically my class is a container, which saves every user-added property to self._meta
which is a dictionary.
class Container(object):
def __init__(self, **kwargs):
super(Container, self).__setattr__('_meta', OrderedDict())
#self._meta = OrderedDict()
super(Container, self).__setattr__('_hasattr', lambda key : key in self._meta)
for attr, value in kwargs.iteritems():
self._meta[attr] = value
def __getattribute__(self, key):
try:
return super(Container, self).__getattribute__(key)
except:
if key in self._meta : return self._meta[key]
else:
raise AttributeError, key
def __setattr__(self, key, value):
self._meta[key] = value
#usage:
>>> a = Container()
>>> a
<__main__.Container object at 0x0000000002B2DA58>
>>> a.abc = 1 #set an attribute
>>> a._meta
OrderedDict([('abc', 1)]) #attribute is in ._meta dictionary
I have some classes which inherit Container
base class and some of their methods have @property decorator.
class Response(Container):
@property
def rawtext(self):
if self._hasattr("value") and self.value is not None:
_raw = self.__repr__()
_raw += "|%s" %(self.value.encode("utf-8"))
return _raw
problem is that .rawtext
isn't accessible. (I get attributeerror.) every key in ._meta
is accessible, every attributes added by __setattr__
of object
base class is accessible, but method-to-properties by @property decorator isn't. I think it has to do with my way of overriding __getattribute__
in Container
base class. What should I do to make properties from @property
accessible?