Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Python properties work?

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?

like image 872
Fred Foo Avatar asked May 31 '11 21:05

Fred Foo


People also ask

How do properties work in Python?

Python's property() is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property() is a built-in function, you can use it without importing anything.

How is a property created?

Public property is created when the government builds some building with the use of tax money. Was this answer helpful?

What does property decorator do in Python?

@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property(). Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters.


1 Answers

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.hello lies in how the property implements the __get__(self, instance, owner) special method:

  • If a descriptor is accessed on an instance, then that instance is passed as the appropriate argument, and owner is the class of that instance.
  • When it is accessed through the class, then instance is None and only owner is passed. The property object recognizes this and returns self.

Besides the Descriptors howto, see also the documentation on Implementing Descriptors and Invoking Descriptors in the Language Guide.

like image 96
Tim Yates Avatar answered Oct 07 '22 20:10

Tim Yates