Reputation: 1851
Is it possible to merge two classes' methods like so?
class foo:
def __init__(self):
self.active = False
def doThing(self):
if not self.active: return
print("Just a foo here, boss")
class bar(foo):
def __init__(self):
self.active = False
def doThing(self):
print("I shouldn't be showing unless I'm active!")
f = foo()
b = bar()
f.doThing()
b.doThing()
This will output "I shouldn't be showing unless I'm active!" when I want it to inherit the self.active checking part of the parent class and thus make the method return before the rest of it runs. Is there a way to do this?
Upvotes: 0
Views: 211
Reputation:
The other answers are correct, merging the functions does not make any sense. Though if you want to implement the second class and merge it in an OOP manner, the code is below.
class Bar(Foo):
def __init__(self):
super().__init__()
def doThing(self):
super(self).doThing()
if not self.isActive(): return
print("I shouldn't be showing unless I'm active!")
Upvotes: 0
Reputation: 117681
You can put the check in a separate function:
class Foo:
def __init__(self):
self.active = False
def isActive(self):
return self.active
def doThing(self):
if not self.isActive(): return
print("Just a Foo here, boss")
class Bar(Foo):
def __init__(self):
super().__init__()
def doThing(self):
if not self.isActive(): return
print("I shouldn't be showing unless I'm active!")
Or alternative:
class Foo:
def __init__(self):
self.active = False
def doThing(self):
if not self.active: return
return self.doPrint()
def doPrint(self):
print("Just a Foo here, boss")
class Bar(Foo):
def __init__(self):
super().__init__()
def doPrint(self):
print("I shouldn't be showing unless I'm active!")
Upvotes: 2