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

前端 未结 7 2126
清酒与你
清酒与你 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:34

    In this particular case, you could define two properties, which call an underlying function:

    class A:
        @property
        def x(self):
            return self._x(neg = False)
    
        @property
        def x_neg(self):
            return self._x(neg = True)
    
        def _x(self, neg):
            return 5 if not neg else -5
    

提交回复
热议问题