基于init

时间:2018-06-05 11:23:20

标签: 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

    def method2(self):
        #do something here 

我想要一种工厂类,根据输入,它等于MyClass1MyClass2。我试过了:

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成为MyClass1MyClass2个实例,但看不到method3。我应该如何修改我的代码?我怀疑我需要修改Children.__new__方法。

0 个答案:

没有答案