Search code examples
pythonobjectdata-structures

Add variable value for a specific variable but in another class


I have two classes, ClassA and ClassB, that both have variables var1 and var2. In ClassA, var1 is initialized to 1 and var2 is initialized to 2. ClassB inherits from ClassA. I want to be able to define/set the value of var1 in ClassB using the value of var1 from ClassA. Is there a way to do this in Python, similar to the set method used in Java?


Solution

  • ClassB inherits ClassA, so it will have var1 if you call ClassA __init__. You need to do it from ClassB __init__ instead of creating seperate object and sending it as value

    class ClassB(ClassA):
        def __init__(self):
            super().__init__()
    
    object2 = ClassB()
    print(object2.var1) # 1