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.
In
getVar1Var2AsString, when you callParent.getVar1(), you do so without any reference to the current object or its class. It always looks up the methods onParent. If you want to look up the methods in the current object's class, useself.getVar1(). You also don't need the getter methods at all, you can just useself.var1andself.var2.