Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading