Home > Software engineering >  class Foo(), get remainder, after division input by 100
class Foo(), get remainder, after division input by 100

Time:11-21

what's best way to make the class Foo():

>>> p=Foo()
>>> print (p.x) => p.x = 0

>>> p.x = 125
>>> print (p.x) => p.x = 25 (tens of 125)

CodePudding user response:

You can use getters and setters. Depending on whether you want to store the remainder or the unmodified value in the instance, place the logic to calculate the remainder in either the setter or getter, respectively.

class Foo:                                   
    def __init__(self):                      
        self._x = 0                          
                                             
    @property                                
    def x(self):                             
        return self._x                       
                                             
    @x.setter                                
    def x(self, x):                          
        self._x = x % 100

(As a side note, defaulting to using getters and setters (as is common in some other languages) is considered unpythonic. Here they (or some variation of it) are needed to alter the value set or retrieved according to your rule/requirement.)

  • Related