Object default value
Larry Bates
larry.bates at websafe.com
Tue Sep 20 15:51:52 EDT 2005
The prints can be done by defining an __str__ method on the
class, but I don't think you will get the type(obj) to work
the way you want.
class obj(object):
__default=1
y=2
def __str__(self):
return str(self.__default)
myobj=obj()
print "myobj=", myobj
print "myobj.y=", myobj.y
>>> myobj= 1
>>> myobj.y= 2
ago wrote:
> 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