Eugene S
Eugene S

Reputation: 6910

How to use derived class variable in baseclass method

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?

Upvotes: 1

Views: 232

Answers (1)

Brian L
Brian L

Reputation: 3251

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

Upvotes: 3

Related Questions