setting up dynamic descriptors in Python

brian huggins bghugg at aol.com
Thu Sep 24 11:14:39 EDT 2009


Hello,

I want to set up descriptors at runtine, but it isn't working the way
i would expect.  Does anybody know if this is possible?  Here is an
example:

class Descriptor(object):
    def __init__(self, name) :
        self.val=0
        self.name = name

    def __get__(self, obj, objtype):
        print 'Retrieving', self.name
        return self.val

    def __set__(self, obj, val):
        print 'Updating' , self.name
        self.val = val

class TestDesc (object):
    x=Descriptor ("x")
    def __init__ (self):
        self.y=Descriptor("y")

And Usage:
>>> test=TestDesc()
>>> test.x=0
Updating x
>>> test.x=4
Updating x
>>> test.x
Retrieving x
4
>>> test.y
<descriptor.Descriptor object at 0x00B3A5F0>

When i access y, it appears to be a regular object and not a
descriptor type object like x.  Is there a way to make y work the same
as x but setting it up during object creation?

thanks,
brian







More information about the Python-list mailing list