What is a property object?

后端 未结 3 966
失恋的感觉
失恋的感觉 2021-02-18 21:48

I am not new to python, but I have a pretty basic question here.

I was playing around with python and found that there is the type property

>>>          


        
3条回答
  •  一整个雨季
    2021-02-18 22:28

    The property object is what you are actually thinking of as a property. Consider this example:

    class Foo(object):
        def __init__(self):
            self._bar = 0
    
        @property
        def bar(self):
            return self._bar + 5
    

    Foo.bar is a property object which has a __get__ method. When you write something like

    x = Foo()
    print(x.bar)
    

    the lookup for x.bar finds that type(x).bar has a __get__ method, and so the attribute lookup becomes equivalent to

    type(x).bar.__get__(x, type(x))
    

    which produces the value x._bar + 5.

    The use of property as a decorator somewhat obscures the fact that bar is a property object. An equivalent defintion is

    class Foo(object):
         def __init__(self):
             self._bar = 0
    
         bar = property(lambda self: self._bar + 5)
    

    which shows more explicitly that you are creating a property object with the given lambda expression as the getter for that property, and binding the object to the class attribute bar.

    The property class (along with instance methods, class methods, and static methods) is a specific application of Python's general descriptor protocol, which defines the behavior of class attributes with __get__, __set__, and/or __del__ methods.

提交回复
热议问题