Re: Dynamic use of property() fails



En Mon, 14 Apr 2008 22:43:39 -0300, andrew cooke <andrew@xxxxxxxxxx> escribió:

This is my first attempt at new classes and dynamic python, so I am
probably doing something very stupid... After reading the how-to for
descriptors at http://users.rcn.com/python/download/Descriptor.htm I
decided I would make an object that returns attributes on read, but on
setting calls an arbitrary function.

My code looks like:
class ActiveDAO(object):
def __init__(self):
self.__values__ = {}
def add_field(self, name, value, on_change):
self.__values__[name] = value
def get(self): return self.__values__[name]
def set(self, new_value): self.__values__[name] =
on_change(new_value)
def delete(self): raise AttributeError
self.__dict__[name] = property(get, set, delete)

However, when I try to use this (in a test) with code like:
dao = ActiveDAO()
dao.add_field("name", "value", lambda _: None)
assertEqual(dao.name, "value")

I get a failure because lookup of the attribute is returning
"<property object at 0x6b8910>".

That is quite reasonable, but I was under the expression that some
magic was supposed to happen, as described in the document referenced
above!

The "magic" happens when the descriptor is found in the *class*, not in the instance. I think it's detailed in Hettinger's document.
Do you actually want "per-instance" defined properties?

__special__ names are reserved for Python internal usage; don't use them. Implementation-only attributes ("private" ones) are spelled with a single underscore.


--
Gabriel Genellina

.



Relevant Pages

  • Dynamic use of property() fails
    ... This is my first attempt at new classes and dynamic python, ... After reading the how-to for ... descriptors at http://users.rcn.com/python/download/Descriptor.htm I ... def delete: raise AttributeError ...
    (comp.lang.python)
  • Readonly attributes ...
    ... even reading the threads about "properties" and "descriptors", ... def setX: ... the developper can set the attribute 'x' ...
    (comp.lang.python)
  • Re: Typed Parameters
    ... foofunc(FooClass foo, clever, smart, stupid) ... def cool ... args.shift.cool_string(self, *args) ... args.shift.cool_string_hash(str, self) ...
    (comp.lang.ruby)
  • Newbie completely confused
    ... Now reading ... ... The original problem showed up using Python 2.4.3 under linux. ... class SmallClass: ... def input: ...
    (comp.lang.python)
  • Re: lambda with $1 fails as gsub block
    ... def meth ... una macchina intelligente che aiuta le persone ... delle persone intelligenti. ... Computers are not smart to help stupid people, ...
    (comp.lang.ruby)