Object default value

ago agostino.russo at gmail.com
Tue Sep 20 15:31:19 EDT 2005


Is it possible to have a default value associated python objects? I.e.
to flag an attribute in such a way that the assignment operator for the
object returns the default attribute instead of the object itself, but
calls to other object attributes are properly resolved? (I don't think
so, but I am not sure)

Example:

class obj(object):
 x=1 #assume x is somehow made into a default value
 y=2

Ideally this should be the result:

myobj=obj()
print myobj #-> 1
print myobj.y #-> 2
x=myobj
print x #-> 1
print type(x) #int

Those are my half-working solutions so far:

1) using __get__ descriptor within the class,

def __get__(self,parent,parenttype): return self.x

then

print myobj #works
print myobj.y #does not work! equivalent to: print 1.y

2) Use a __call__ method without a __get__ descriptor.

def __call__(self): return self.x

then:

print myobj() #works, but not the same as: print myobj
print myobj.y #works




More information about the Python-list mailing list