2

I am trying to create object properties from a function, like this:

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

    x = property(get_x)
    neg_x = property(get_x(neg=True))

I have tried following the advice from a previous Stack Overflow post, but with an added property neg_x I get this confusing error message:

TypeError: get_x() takes at least 1 argument (1 given)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Eddy
  • 6,661
  • 21
  • 58
  • 71

2 Answers2

3

When you try to assign:

neg_x = property(get_x(neg=True))

you are actually calling get_x, without the instance for self, and trying to pass the result (which would be -5, and therefore not a getter) to property. A much neater way to do this is:

class A:

    @property
    def x(self):
        return 5

    @property
    def neg_x(self):
        return -self.x

If you really want to use the function, you could use e.g. lambda (or functools.partial) to call the function when the property is accessed, rather than when defining it:

class A:

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

    x = property(get_x)

    neg_x = property(lambda self: self.get_x(neg=True))

In use:

>>> a = A()
>>> a.x
5
>>> a.neg_x
-5
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

I think this will work for you: just pass value. of your neg. Check the last line.

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

    x = property(get_x)
    neg_x = property(get_x(True))
Projesh Bhoumik
  • 1,058
  • 14
  • 17