Reputation: 23644
The answer to this question is probably "W-what!? What the !@#$-- Stop!! That's a terrible idea!", but I would like to hear your thoughts...
I have two classes and one inherits from the other.
class A(object):
def t1(self):
self.t2()
def t2(self):
print "A"
class B(A):
def t1(self):
super(B, self).t1()
def t2(self):
print "B"
>>> a = A()
>>> b = B()
>>> a.tl()
A
>>> b.t1()
B
In this example B.t1
calls the super
function, to call A.t1
, but when it hits self.t2()
, in the A.t1
function it returns to the B
class to perform B.t2()
How would I be able to force calls from the base class to stay in the base class? This is all I could come up with, and it works, but I'm thinking there's a better solution.
class A(object):
def t1(self):
if type(self) == A:
self.t2()
else:
super(type(self), self).t2()
def t2(self):
print "A"
class B(A):
def t1(self):
super(B, self).t1()
def t2(self):
print "B"
>>> a = A()
>>> b = B()
>>> a.tl()
A
>>> b.t1()
A
Upvotes: 0
Views: 44
Reputation: 131
You use double underscore aka name mangling.
class A(object):
def t1(self):
self.__t2() # <---- changed the call
def t2(self):
print "A"
__t2 = t2 # private copy of original t2() method
>>> a = A()
>>> b = B()
>>> a.tl()
A
>>> b.t1()
A
But name mangling has a huge default : it make unittesting more difficult and ugly if the function has only the double underscore as name.
But I'm with @BrenBarn, it feel like a fragile design.
Upvotes: 1
Reputation: 251448
In A
's t1
you can do A.t2(self)
. However, this kind of setup is probably an indicator of a fragile design.
Upvotes: 1