Python: How to pass more than one argument to the property getter?

前端 未结 7 1987
清酒与你
清酒与你 2021-01-31 06:48

Consider the following example:

class A:
    @property
    def x(self): return 5

So, of course calling the a = A(); a.x will retur

7条回答
  •  旧巷少年郎
    2021-01-31 07:36

    I think you did not fully understand the purpose of properties.

    If you create a property x, you'll accessing it using obj.x instead of obj.x(). After creating the property it's not easily possible to call the underlying function directly.

    If you want to pass arguments, name your method get_x and do not make it a property:

    def get_x(self, neg=False):
        return 5 if not neg else -5
    

    If you want to create a setter, do it like this:

    class A:
        @property
        def x(self): return 5
    
        @x.setter
        def x(self, value): self._x = value
    

提交回复
热议问题