0

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++?

1
  • You are calling parent instance variable and overrites it in your child class. In Your parent class return Parent.CONST_VAL ,so that when python interpreter runs it knows from where to pick the value of CONST_VAL Commented Nov 3, 2020 at 11:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.