inheritance - Avoid using child method in parent class in python -
suppose have 2 classes in python 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 call fun2
of child
from child import child test = child() test.fun2()
i output:
c.fun1 p.fun2 c.fun2
which means call of child.fun2()
leads parent.fun2()
. inside parent.fun2()
, use self.fun1()
in case interpreted child.fun1()
in test.
but want class parent
individual , call of parent.fun2()
uses parent.fun1()
inside it.
how can avoid this?
i know can make parent.fun1()
private parent.__fun1()
. have instances of parent
need use parent.fun1()
outside class. means need override fun1()
.
that's how inheritance supposed work. behavior need, might want reconsider parent
& child
class's relationship, or change method names or @ least make parent
methods classmethods
or staticmethods
.
this should work need, don't it.
class parent(object): def __init__(self): self.num=0 def fun1(self): print 'p.fun1' def fun2(self): parent.fun1(self) print 'p.fun2'
child
class can remain same.
in classes accessed in inheritance chain, self
point instance of class instantiated , not current class accessed in super
call (or in order find method/attribute matter). self.fun2
point method of child
class.
Comments
Post a Comment