I’ve been successfully using Python properties, but I don’t see how they could work. If I dereference a property outside of a class, I just get an object of type property:
@property
def hello(): return "Hello, world!"
hello # <property object at 0x9870a8>
But if I put a property in a class, the behavior is very different:
class Foo(object):
@property
def hello(self): return "Hello, world!"
Foo().hello # 'Hello, world!'
I’ve noticed that unbound Foo.hello is still the property object, so class instantiation must be doing the magic, but what magic is that?
As others have noted, they use a language feature called descriptors.
The reason that the actual property object is returned when you access it via a class
Foo.hellolies in how the property implements the__get__(self, instance, owner)special method:owneris the class of that instance.instanceis None and onlyowneris passed. Thepropertyobject recognizes this and returnsself.Besides the Descriptors howto, see also the documentation on Implementing Descriptors and Invoking Descriptors in the Language Guide.