1

I have a hierarchy of classes that inherit from each other that look something like that:

class BaseClass(object):
    def __init__(self):
        self.localLog = logging.getLogger(testName)
        self.var1 = 'a'

    def printVar(self):
        print self.var1

class SubClass1(BaseClass):
    def __init__(self):
        self.var1 = 'b'
        super(SubClass1, self).__init__()

class SubClass2(SubClass1):
    def __init__(self):
        self.var1 = 'c'
        super(SubClass2, self).__init__()

Now I want to instantiate SubClass2 and call BaseClass printVar method with SubClass2 local var1 variable:

obj = SubClass2()
obj.printVar()

What I want to happen is for variable c climb all the way up to the BaseClass and be passed to the printVar method. However, what I get is the variable a instead.

I realize that I will get the desired result by removing the super lines but I have to keep them to have access to the self.localLog variable in all inheriting classes.

Is there a way to achieve what I want or should I just keep a local printVar method for each class?

2
  • 2
    Why are you setting self.var1 before you call super()? Doing means that a superclass's definition can override it. Commented Feb 25, 2015 at 3:35
  • @CharlesDuffy You are absolutely right! My miss. Thanks! Commented Feb 25, 2015 at 3:42

1 Answer 1

3

Seems like you can easily solve the problem simply by calling super(...).__init__() before setting var1 in your subclasses.

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.