如何在没有元类的情况下将不同的参数传递给 __new__ 和 __init__ 函数。

5 浏览
0 Comments

如何在没有元类的情况下将不同的参数传递给 __new__ 和 __init__ 函数。

我有一个简单的基类,它实例化为两个子类之一:

class Base:
    def __new__(cls, select):
        return super().__new__(Child1 if select == 1 else Child2)
    def __init__(self, select):
        self.select = select
    def __repr__(self):
        return f'{type(self).__name__}({self.select})'
class Child1(Base):
    def __init__(self):
        super().__init__('One')
class Child2(Base):
    def __init__(self):
        super().__init__('Two')

这段代码目前会引发错误,因为子类的`__init__`方法不接受任何参数,而父类的`__new__`方法接受一个参数:

>>>> Base(1)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: __init__() takes 1 positional argument but 2 were given

我可以通过在一个新的元类中重写`type.__call__`来解决这个问题,但我想保持`type`作为我的元类。

我也可以将`select`或`*args`添加为子类`__init__`方法的参数。有没有更优雅的方法来实现允许子类的`__init__`使用与父类的`__new__`不同的参数?

0