Descriptor puzzlement
Peter Otten
__peter__ at web.de
Thu Jan 8 08:05:17 EST 2004
John Roth wrote:
> Using Python 2.2.3, I create this script:
>
> [beginning of script]
>
> class AnObject(object):
> "This might be a descriptor, but so far it doesn't seem like it"
> def __init__(self, somedata):
> self.it = somedata
> def __get__(self, obj, type=None):
> print "in get method"
> return self.it
> def __set__(self, obj, it):
> print "in set method"
> self.somedata = it
> return None
> ## def foo(self):
> ## return 1
>
> class AnotherObject(object):
> def __init__(self):
> self.prop = AnObject("snafu")
>
> myClass = AnotherObject()
> print myClass.prop
> myClass.prop = "foobar"
> print myClass.prop
>
> [end of script]
>
> Then I execute it:
>
> C:\Documents and Settings\John\My Documents\Projects\AstroPy4>b
>
> C:\Documents and Settings\John\My Documents\Projects\AstroPy4>python b.py
> <__main__.AnObject object at 0x0086D248>
> foobar
>
> It doesn't look like the descriptor protocol is getting
> invoked at all.
>
> What's happening here?
The descriptor protocol works on the class, not the instance, so
class AnotherObject(object):
prop = AnObject("snafu")
or something similar should work. This means in particular that you have to
store the property's state in the AnotherObject rather than the AnObject
instance.
Peter
More information about the Python-list
mailing list