The name title
won't exist in the body of the class until you first create it.
The fact is that what allows getters and setters to exist in this way in Python is the descriptor protocol - with a helper callable named property{ . Back in the old times (circa Python 2.4), it was found out that if property taking a single argument would return a
propertyobject with a
.setter` attribute, this attribute could be used as a decorator to register the setter method for the same object.
Prior to that one had to declare the getter, setter and deleter as ordinary methods, and create the property object with a line like
title = property(title_getter, title_setter, tittle_deleter)
in the class body.
Thus, if you do:
class MyClass:
def __init__(self):
self.title = None
@property
def title(self):
return self._title
@title.setter
def title(self, title):
print 'TITLE SETTER: %s' % title
self._title = title
your code will work, because property
is called with the
function title
as a parameter - it then returns a property
object,
which have a __get__
method that will cause that original
title
function to be called, and a setter
and deleter
attributes,
which are callables - the title.setter
when used as a decorator,
just add it internally to the property object, so that its __set__
method
will cause it to be invoked. (The working of the descriptor protocol and the __set__
, __delete__
and __get__
methods, used internally by property
is described in the language Data Model document)