What is a property object?

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

提交回复
热议问题