Python init中基于参数的动态继承
我有两门不同的课:Python init中基于参数的动态继承,python,python-3.x,oop,Python,Python 3.x,Oop,我有两门不同的课: 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
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
的children类:
class Children(MyMainClass):
def __init__(self, x_or_s):
pass
def method3(self):
#do something
通过这样做,
子类
成为MyClass1
或MyClass2
实例,并且看不到method3
。我应该如何修改我的代码?我怀疑我需要修改Children.\uuuuuuuuu
方法。确实是Children.method3
取决于x\u或
的类型?不。但我认为这不会影响正确答案。既然method3
不取决于x\u或的类型,将method3
移到一个(新的)位置有意义吗MyClass1
和MyClass2
继承自的基类?是的,可能是这样,但是对于纯组织method3
应该属于子类
您能解释为什么应该是这样吗?通用oop原则建议通用方法属于基类,而更具体的方法属于子类。由于method3
似乎是通用的(对于MyClass1
和MyClass2
的行为相同),它似乎属于基类。