[Tutor] @property for old style classes vs new style classes
Steven D'Aprano
steve at pearwood.info
Thu Sep 15 12:57:12 EDT 2016
On Thu, Sep 15, 2016 at 04:40:22AM +0000, monikajg at netzero.net wrote:
> Could somebody please explain what is going on for old style classes for the below code:
The important part is that the descriptor protocol doesn't get used for
old style classes. If that statement means something to you, that's
great, otherwise please ask. So in an old-style class:
> class GetSet():
>
> def __init__(self, value):
> self.attrval = value
>
> @property
> def var(self):
> print "getting the var attribute"
> return self.attrval
> @var.setter
> def var(self,value):
> print "setting the var attribute"
> self.attrval = value
At this point, you have a class GetSet, with a class attribute:
GetSet.var
which is a property object. Now let's make an instance:
> me = GetSet(5)
> me.var = 1000
At this point, the instance now has an instance attribute:
me.var
which is the int 1000. So there are now TWO attributes called "me",
living in different scopes:
me.__dict__['var'] = 1000 # in the instance
GetSet.__dict__['var'] = property object
Remember that attribute look-ups normally look in the instance __dict__
before the class __dict__.
> print me.var
> del me.var
> print me.var
The first print looks for 'var' in the instance, finds it, and prints
1000. Then the del command looks for 'var' in the instance, finds it,
and deletes it. Then finally the second print looks for 'var' in the
instance, *doesn't* find it there (because it has been deleted), so it
looks in the class, and finds GetSet.__dict__['var'] which is a property
object.
At this point, things get a bit mysterious. According to the
documentation, Python ought to print something like:
<property object at 0x123456>
since the descriptor protocol doesn't run for old-style classes. But
apparently it does *partly* run, because the property object's __get__
method is invoked, which calls the getter method that you defined.
> Output:
> 1000
> getting the var attribute
> 5
So there is a part mystery here. As far as I can tell, the documentation
suggests that the output should be:
1000
<property object at 0x...>
rather than what you got.
--
Steve
More information about the Tutor
mailing list