0

How can I change a class object with some rules when it assigned? for example:

class Foo:
    x=0
    if x < 0:
        x = -1
    else:
        x = 1


p = Foo()
p.x = 1234
print(p.X)

So when I print p.x I expect 1 to be printed. but 1234 is printed. What should I do?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
myregm
  • 67
  • 1
  • 8

2 Answers2

1

The first x = 0 you declare is a class attribute. It is the same for all objects of the class.

When you write p.x, you create an instance attribute, a value of x that belongs to that specific object. That hides the Foo.x in that particular object (that's how the python attribute lookup works).

However, that value remains the default for other objects of the class, eg, if you create a new object

foo2 = Foo()
print(f2.x) # prints 1
blue_note
  • 27,712
  • 9
  • 72
  • 90
0

You have to make x a property, with a setter function:

class Foo:
    def __init__(self):
        self.x = 1

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        if value < 0:
            value = -1
        else:
            value = 1

        self._x = value

This makes it so the function decorated with @x.setter is executed whenever an assignment to the x attribute is performed:

>>> foo = Foo()
>>> foo.x = 1234
>>> foo.x
1
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149