Suppose I have two classes in Python as below:
class Parent(object):
def __init__(self):
self.num = 0
def fun1(self):
print 'p.fun1'
def fun2(self):
self.fun1()
print 'p.fun2'
and
from parent import Parent
class Child(Parent):
def __init__(self):
super(Child,self).__init__()
def fun1(self):
print 'c.fun1'
def fun2(self):
super(Child, self).fun2()
print 'c.fun2'
and if I call fun2 of Child
from child import Child
test = Child()
test.fun2()
I get output:
c.fun1
p.fun2
c.fun2
Which means the call of Child.fun2() leads to Parent.fun2(). But inside the Parent.fun2(), I use self.fun1() which in this case interpreted as Child.fun1() in my test.
But I really want the class Parent to be individual and the call of Parent.fun2() always uses Parent.fun1() inside it.
How can I avoid this?
I only know that I can make Parent.fun1() private into Parent.__fun1(). But I also have some instances of Parent where I need to use Parent.fun1() outside this class. That means I really need to override the fun1().
Parentany uses ofself.fun1()only refer toParent.fun1(). In my test, since I create an instance ofChild, the use ofChild.fun2()lead toParent.fun2(). And this call forParent.fun2()calls for Child.fun1(), but I want it to call forParent.fun1(). I hope the output becomep.fun1 p.fun2 c.fun2fun1in the child class?super, since that happens automatically if the method doesn't exist in the derived class. So you can get rid of the__init__inChild.