我想这样做:
class A:
def methodA(self):
return 5
class B:
def methodB(self):
return 10
class X(...):
def __init__(self, baseclass):
if baseclass =='A' : derive X from A
elif baseclass == 'B' : derive X from B
else: raise Exception("Not supported baseclass %s!" % (baseclass))
def methodX(self):
return 42
X('A').methodA() # returns 5
X('A').methodX() # returns 42
X('A').methodB() # methodB not defined
X('B').methodB() # returns 10
X('B').methodX() # returns 42
X('A').methodA() # methodA not defined
我该如何实现这一点?你知道吗
如果要将
methodX
添加到现有类中,可以考虑多重继承:您可以将arg和kwarg添加到
X.new
,并将它们传递给特定的构造函数。以下是您的测试结果(我更正了您问题的最后一个):应该定义两个类
X
和Y
,以及一个工厂方法来实例化X或Y,具体取决于参数。你知道吗一般来说,您尝试实现的行为有些混乱。创建实例时(这就是
X(...)
所做的),应该得到X
的实例,并且类的实例应该具有相同的属性。这是类存在的主要原因之一。你知道吗示例:
将打印
相关问题 更多 >
编程相关推荐