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

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)


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

a property should only depend on the related object. If you want to use some external parameters, you should use methods.


In your second example, you're using a.x() as if it were a function: a.x(neg=True). With this in mind, why not just define it as a function?


I know this question is old, but, for reference, you can call your property with an argument like that:

a = A()
assert a.x == 5
assert A.x.fget(a, True) == -5

As mentioned by others, this is not advised.