
On Thu, May 28, 2009 at 8:22 AM, kirby urner<kirby.urner@gmail.com> wrote: << SNIP >>
I was reading about descriptors, again per Holden workshop, and noticing the author adding at class level, but never making use of the passed instance argument, only self (inside the descriptor).
Below is the example from the other book, for contrast. Note how the "instance" variable is not used in __set__ or __get__, so whereas it looks like you're getting a new attribute there at the end (new_att), you're not getting anything new at instance level. David's exposition was clearer. ============== Let's create a data descriptor, and use it through an instance:
class UpperString(object): ... def __init__(self): ... self._value = '' ... def __get__(self, instance, klass): ... return self._value ... def __set__(self, instance, value): ... self._value = value.upper() ... class MyClass(object): ... attribute = UpperString() ... instance_of = MyClass() instance_of.attribute '' instance_of.attribute = 'my value' instance_of.attribute 'MY VALUE' instance.__dict__ = {}
Now if we add a new attribute in the instance, it will be stored in its __dict__ mapping:
instance_of.new_att = 1 instance_of.__dict__ {'new_att': 1}
But if a new data descriptor is added in the class, it will take precedence over the instance __dict__:
MyClass.new_att = MyDescriptor() instance_of.__dict__ {'new_att': 1} instance_of.new_att '' instance_of.new_att = 'other value' instance_of.new_att 'OTHER VALUE' instance_of.__dict__ {'new_att': 1}
============= Expert Python Programming: Learn best practices to designing, coding, and distributing your Python software Tarek Ziadé Copyright © 2008 Packt Publishing