Search code examples
pythonclassinheritanceself

How to define a class inherited from the Zero class that allows you to modify the self._x variable


This is my Zero class:

class ZeroClass():
    def __init__(self, x):
        self._x = x
    def __call__(self, w):
        return w * self._x

If I run the code below, it returns 500:

s = ZeroClass(100.)
print(s(5))

Now, I need to implement the class 'AdjustZero' allowing to change the variable self._x through xSet method

class AdjustZero(ZeroClass):
    def xSet():

How can this be done?


Solution

  • You just have to assign the variable like that. I assumed that your Zero class is just your Scale class.

    class Scale:
        def __init__(self, x):
            self._x = x
    
        def __call__(self, w):
            return w * self._x
    
    
    class AdjustZero(Scale):
        def xSet(self, x):
            self._x = x
    
    
    s = AdjustZero(100.)
    print(s(5))
    s.xSet(10)
    print(s(5))
    

    The output is :

    500.0
    50