What is a property object?

后端 未结 3 955
失恋的感觉
失恋的感觉 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:05

    A property is an attribute object containing a getter and a setter method.

    0 讨论(0)
  • 2021-02-18 22:09
    class MyClass:
        def __init__(self,*costs):
            self.costs = costs
        def item_cost(self):
            return sum(self.costs)
    

    now you can do

    MyClass(1,2,3,4).item_cost() #prints 10
    

    but we can make it a property

    class MyClass:
        def __init__(self,*costs):
            self.costs = costs
        @property
        def item_cost(self):
            return sum(self.costs)
    

    and now we can access it as a simple variable

    MyClass(1,2,3,4).item_cost
    

    you could also create a setter for the value with

      ...
       @item_cost.setter
       def set_item_cost(self,value):
             pass #do something with value
      ...
     MyClass(1,2,3,4).item_cost = "yellow"
    

    In general I find them to be sort of an anti-pattern... but some folks like em

    (side note you could also make it a property using it as a regular function instead of a decorator MyClass.item_cost_prop = property(MyClass.item_cost) )

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题