[Tutor] @property for old style classes vs new style classes

eryk sun eryksun at gmail.com
Thu Sep 15 10:08:12 EDT 2016


On Thu, Sep 15, 2016 at 4:40 AM, monikajg at netzero.net
<monikajg at netzero.net> wrote:
> 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
>
>     @var.deleter
>     def var(self):
>         print "deleting the var attribute"
>         self.attrval = None
>
> me = GetSet(5)
> me.var = 1000

A classic instance has both a type (`instance`) and a __class__ (e.g.
GetSet). The type defines how getting, setting, and deleting
attributes works, and the hard-coded classic behavior for calling the
class __getattr__, __setattr__, and __delattr__ methods.

If the class doesn't define __setattr__ and __delattr__, the instance
type sets and deletes attributes directly in the instance dict. Unlike
new-style classes, a data descriptor defined by the class gets ignored
here.

Getting attributes also prefers the instance dict. However, to support
bound methods (e.g. __init__), it falls back on a class lookup and
calls the descriptor __get__ method if defined. Unintentionally, it
happens that this partially supports the property descriptor. But
since there's no data descriptor support, it's only useful for
read-only properties.


More information about the Tutor mailing list