Descriptor puzzlement

Mirko Zeibig mirko-lists at zeibig.net
Thu Jan 8 14:03:47 CET 2004


John Roth said the following on 01/08/2004 01:34 PM:
> 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
Hm, I don't know __set__ and __get__, there are __getattr__ (or 
__getattribute__) and __setattr__ for dynamically assigning attributes. 
Or take a look at properties 
(http://www.python.org/2.2/descrintro.html#property)

> class AnotherObject(object):
>     def __init__(self):
>         self.prop = AnObject("snafu")
> 
> myClass = AnotherObject()
> print myClass.prop
Now just do:
print id(myClass.prop) to see the internal reference.

> myClass.prop = "foobar"
Here you bind an immutable string-object to myClass.prop, the object of 
type AnObject you have bound before has no further references in the 
code and will be garbage collected.

If you create a destructor for AnObject:

   def __del__(self):
     print "%s.__del__" % self

you will see that this happens immediately.

> print myClass.prop

Regards
Mirko



More information about the Python-list mailing list