-1

I want to create a class in python that has setters for its attributes.

For example suppose we have a class named myClass and it has x attribute. I want to create it so that when someone changes x value, only two last digits of x (x % 100) are saved.

using myClass in python shell:

>>> obj = myClass()
>>> obj.x = 352562
>>> obj.x
62

Can I define a setter that is called automatically when changing the value of x?

lucascaro
  • 16,550
  • 4
  • 37
  • 47

1 Answers1

0

You can use properties decorators

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

@x.setter
def x(self, value):
    self._x = value % 100

Also you will have to declare and initialise _x in your init method for a safer code

See this stack overflow post for more information

Treizh
  • 322
  • 5
  • 12