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

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

    Note that you don't have to use property as a decorator. You can quite happily use it the old way and expose the individual methods in addition to the property:

    class A:
        def get_x(self, neg=False):
            return -5 if neg else 5
        x = property(get_x)
    
    >>> a = A()
    >>> a.x
    5
    >>> a.get_x()
    5
    >>> a.get_x(True)
    -5
    

    This may or may not be a good idea depending on exactly what you're doing with it (but I'd expect to see an excellent justification in a comment if I came across this pattern in any code I was reviewing)

提交回复
热议问题