*python中的args和**kwargs

2024-09-28 17:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我预感到我是个讨饭的人。我试图制作一些模拟代码,模仿我在这个论坛和网上其他地方看到的做法。然而,当我尝试做一些类似于我所看到的事情时,我收到了一个意外的错误。例如:

class A():
    defined = []
    def __new__(cls, *args, **kwargs):
        new = kwargs['new']
        if not new and len(A.defined)>0:
            x = A.defined[0]
        else:
            # x = super().__new__(cls, *args, **kwargs)
            # if I use this, it raises error: 
            # "TypeError: object.__new__() takes exactly one argument (the type to instantiate)"
            x = super().__new__(cls)
            # this works
        return x

    def __init__(self, value, *args, **kwargs):
        self.value = value
        A.defined.append(self) 

a = A("a", new = True)

为什么会出现这种错误

谢谢


Tags: 代码selfnewifvaluedef错误args