Reputation: 49
Suppose I have a parent class and a child class that inherits from the parent.
class Parent:
def __init__(self)
stubborn()
class Child():
def __init__(self):
super().__init__(self)
I do not want the stubborn method to be called anytime I call the parent constructor in the child class. How do I approach this?
Upvotes: 1
Views: 70
Reputation: 24691
You wouldn't be able to do anything about it in parent.__init__()
without actually changing that function or stubborn()
.
But, as the child, you could stop the stubborn()
method from doing anything important by temporarily making it a stub:
class Child():
def __init__(self):
old_stubborn = self.stubborn
self.stubborn = lambda:None # stub function that does nothing
super().__init__(self)
# put stubborn() back to normal
self.stubborn = old_stubborn
Upvotes: 0
Reputation: 60994
You can define a classmethod
of Parent
that checks whether or not you are in Parent
, then use that to determine whether to call stubborn
class Parent:
def __init__(self):
if self.is_parent():
self.stubborn()
@classmethod
def is_parent(cls):
return cls is Parent
def stubborn(self):
print("stubborn called")
class Child(Parent): pass
p = Parent() # stubborn called
c = Child() # no output
Upvotes: 2