Search code examples
pythonoopinheritancesuper

Class-variables access in super method of Python


Assume, I have similar code:

class Parent:
  CONST_VAL = '1'
  
  def calc(self):
     return self.CONST_VAL

class Child(Parent):
  CONST_VAL = 'child'

  def calc(self):
     return super().calc() + self.CONST_VAL

And then I execute the following:

c = Child()
c.calc()

>> childchild

I expect it to be '1child', but it's not.

Is there a right way to make a class-variable isolation of super methods like in C++?


Solution

  • In both of your methods you use self.CONST_VAL - this is an instance variable.

    When you call super().calc() you indeed call method calc() of Parent class, but it also returns instance variable, which is the same, obviously.

    What you might want to do is to use Parent.CONST_VAL in you parent class.