Pedro Werneck wrote:
If you need direct access to some atribute, use object.__getattribute__.

class DefaultAttr(object):

... def __init__(self, default):
... self.default = default
... def __getattribute__(self, name):
... try:
... value = object.__getattribute__(self, name)
... except AttributeError:
... value = self.default
... return value
...


x = DefaultAttr(99)
print x.a
99

x.a = 10
print x.a
10

Of if you only want to deal with the case where the attribute doesn't exist, you can use getattr, which gets called when the attribute can't be found anywhere else:


py> class DefaultAttr(object):
...     def __init__(self, default):
...         self.default = default
...     def __getattr__(self, name):
...         return self.default
...     
py> x = DefaultAttr(99)
py> x.a
99
py> x.a = 10
py> x.a
10

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to