I have a child class with two parents with identical function names.
I need to decide (based on type of object being created) within the constructor (__init__
) that which parent class' functions need to be called by the object of child. Is there a way to dynamically link/switch default function calls to that of one of the parents. Sample code given below. I don't want to use container-ship of objects as its very difficult to maintain and refactor.
class Square:
def perform(self, num):
print(num * num)
class Cube:
def perform(self, num):
print(num * num * num)
class Exponent(Square, Cube):
def __init__(self, type):
if type == 'square':
# inherit default functions from square <--- ??
else:
# inherit default functions from cube <--- ??
square = Square() # <-- i don't want to do this
cube = Cube() # <-- i don't want to do this
Exponent('cube').perform(2) # --> should print '8'
Exponent('square').perform(2) # --> should print '4'
Exponent('cube').cube.perform(2) # <-- i don't want to do this
Exponent('square').square.perform(2) # <-- i don't want to do this
One way is given below but involves duplicating all parent class functions which is way too much overkill:
class a:
def x (self):
print('a')
class b:
def x (self):
print('b')
class c(a,b):
def __init__(self, type_):
if type_ == 'a':
self.ref = a
else:
self.ref = b
def x(self):
self.ref.x(self)
c('a').x()
c('b').x()
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…