Why Is The property Decorator Only Defined For Classes?

烈酒焚心 提交于 2019-12-03 12:12:38

This is related to a combination of two factors: first, that properties are implemented using the descriptor protocol, and second that modules are always instances of a particular class rather than being instantiable classes.

This part of the descriptor protocol is implemented in object.__getattribute__ (the relevant code is PyObject_GenericGetAttr starting at line 1319). The lookup rules go like this:

  1. Search through the class mro for a type dictionary that has name
  2. If the first matching item is a data descriptor, call its __get__ and return its result
  3. If name is in the instance dictionary, return its associated value
  4. If there was a matching item from the class dictionaries and it was a non-data descriptor, call its __get__ and return the result
  5. If there was a matching item from the class dictionaries, return it
  6. raise AttributeError

The key to this is at number 3 - if name is found in the instance dictionary (as it will be with modules), then its value will just be returned - it won't be tested for descriptorness, and its __get__ won't be called. This leads to this situation (using Python 3):

>>> class F:
...    def __getattribute__(self, attr):
...      print('hi')
...      return object.__getattribute__(self, attr)
... 
>>> f = F()
>>> f.blah = property(lambda: 5)
>>> f.blah
hi
<property object at 0xbfa1b0>

You can see that .__getattribute__ is being invoked, but isn't treating f.blah as a descriptor.

It is likely that the reason for the rules being structured this way is an explicit tradeoff between the usefulness of allowing descriptors on instances (and, therefore, in modules) and the extra code complexity that this would lead to.

Rory Hart

Properties are a feature specific to classes (new-style classes specifically) so by extension the property decorator can only be applied to class methods.

A new-style class is one that derives from object, i.e. class Foo(object):

Further info: Can modules have properties the same way that objects can?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!