Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python init中基于参数的动态继承_Python_Python 3.x_Oop - Fatal编程技术网

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
的行为相同),它似乎属于基类。