how do i create such a thing?

Steven Bethard steven.bethard at gmail.com
Sun Jan 30 23:52:43 CET 2005


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



More information about the Python-list mailing list