@property 装饰器在 Python 中是如何工作的?
问题描述
I would like to understand how the built-in function property
works. What confuses me is that property
can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator.
This example is from the documentation:
property
's arguments are getx
, setx
, delx
and a doc string.
In the code below property
is used as a decorator. The object of it is the x
function, but in the code above there is no place for an object function in the arguments.
How are the x.setter
and x.deleter
decorators created in this case?
The property()
function returns a special descriptor object:
It is this object that has extra methods:
These act as decorators too. They return a new property object:
that is a copy of the old object, but with one of the functions replaced.
Remember, that the @decorator
syntax is just syntactic sugar; the syntax:
really means the same thing as
so foo
the function is replaced by property(foo)
, which we saw above is a special object. Then when you use @foo.setter()
, what you are doing is call that property().setter
method I showed you above, which returns a new copy of the property, but this time with the setter function replaced with the decorated method.
The following sequence also creates a full-on property, by using those decorator methods.
First we create some functions and a property
object with just a getter:
Next we use the .setter()
method to add a setter:
Last we add a deleter with the .deleter()
method:
Last but not least, the property
object acts as a descriptor object, so it has .__get__()
, .__set__()
and .__delete__()
methods to hook into instance attribute getting, setting and deleting:
The Descriptor Howto includes a pure Python sample implementation of the property()
type:
这篇关于@property 装饰器在 Python 中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!