setting up dynamic descriptors in Python

B

brian huggins

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:Retrieving x
4<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
 
G

Gabriel Genellina

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?

class TestDesc (object):
x=Descriptor ("x")
def __init__ (self):
self.y=Descriptor("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?

The descriptor "magic" only happens when the attribute is looked up on the
class; when it's found in the instance itself, nothing special happens.
You cannot attach descriptors to a specific instance, but you can alter
its class at runtime. Basically you have to create a new class (that
inherits from the "real" class and adds the desired descriptor) and set it
as the instance __class__ attribute.
(This was discussed some time ago, try searching the list archives. Uh, I
found this:
http://groups.google.com/group/comp.lang.python/t/bfc093464dd6ba9/
but you should be able to find other threads)
 
B

brian h

I created a new class for each instance as you suggested and added the
descriptor to the class. It worked great. Thanks for the help.

Brian Huggins
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top