How does the @property decorator work in Python?

后端 未结 13 2129
闹比i
闹比i 2020-11-21 04:49

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

13条回答
  •  我寻月下人不归
    2020-11-21 05:35

    The first part is simple:

    @property
    def x(self): ...
    

    is the same as

    def x(self): ...
    x = property(x)
    
    • which, in turn, is the simplified syntax for creating a property with just a getter.

    The next step would be to extend this property with a setter and a deleter. And this happens with the appropriate methods:

    @x.setter
    def x(self, value): ...
    

    returns a new property which inherits everything from the old x plus the given setter.

    x.deleter works the same way.

提交回复
热议问题