pythonoopinheritanceclass-methodclass-variables

How can a child class inherit a class method from its parent that gets a class variable from the child in python?


I have a code here where I define a parent class with class methods and class variables:

class Parent:
    var1 = 'foo'
    var2 = 'bar'
    
    def getVar1Var2AsString(self):
        return f'{Parent.getVar1()}_{Parent.getVar2()}'

    @classmethod
    def getVar1(cls):
        return cls.var1

    @classmethod
    def getVar2(cls):
        return cls.var2

And then, I have a code where I define the child class:

class Child(Parent):
    var1 = 'banana'
    var2 = 'apple'

And then I run:

child = Child()
output = child.getVar1Var2AsString()
print(output)

I expected that the output would return banana_apple, but it returns foo_bar instead.

How can I get the result I expect? I'm kind of new in OOP.


Solution

  • In getVar1Var2AsString, when you call Parent.getVar1(), you do so without any reference to the current object or its class. It always looks up the methods on Parent. If you want to look up the methods in the current object's class, use self.getVar1(). You also don't need the getter methods at all, you can just use self.var1 and self.var2.