我有两个不同的类:
class MyClass1:
def __init__(self, x):
self.x = x #x is expected to be a float
def method1(self):
#do something here
class MyClass2:
def __init__(self, s):
self.s = s # s is expected to be a string
def method2(self):
#do something here
我想要一种工厂类,根据输入,它等于MyClass1
或MyClass2
。我试过了:
class MyMainClass(arg):
def __new__(cls, arg):
if isinstance(arg, float):
return MyClass1(arg)
elif isinstance(arg, str):
return MyClass2(arg)
else:
raise TypeError("either float or str")
这有效,但我有另一个来自MyMainClass
的儿童课程:
class Children(MyMainClass):
def __init__(self, x_or_s):
pass
def method3(self):
#do something
通过这样做,Children
成为MyClass1
或MyClass2
个实例,但看不到method3
。我应该如何修改我的代码?我怀疑我需要修改Children.__new__
方法。