Over my head with descriptors
Christian Kastner
usenet at kvr.at
Sat Dec 16 15:51:50 EST 2006
Sarcastic Zombie wrote:
> Code included below.
>
> Basically, I've created a series of "question" descriptors, which each
> hold a managed value. This is so I can implement validation, and render
> each field into html automatically for forms.
>
> My problem is this: every instance of my "wizard" class has unique self
> values, but they share the exact same descriptor values.
That's because descriptors only work as class attributes, not instance
attributes.
> Meaning, if
>
> t = Test("ar")
> y = Test("ar")
>
> t is y
> False
>
> t.age is y.age
> True
As an attribute of the owner class, the descriptor is instantiated once
for the class itself, and not for every instance of the owner class:
class Foo(object):
# Class attribute
desc = Descriptor()
def __init__(self, value):
# Instance attributes go here
self.value = somevalue
> Code below. What am I not understanding?
> -----------------------------------------
...
> class Question(object):
...
> def __get__(self, instance, owner):
> return self
If you want to do per-instance stuff, use the "instance" argument:
# Warning: simplified
class Descriptor(object):
def __get__(self, instance, owner):
return instance._desc
def __set__(self, instance, value):
instance._desc = value
Chris
More information about the Python-list
mailing list