[英]*args and **kwargs in python
我保證我是 *args 和 **kwargs 的初學者。 我試圖制作一些模擬代碼來模仿我在這個論壇和 .net 上其他地方看到的東西。 但是,當我嘗試做與我所看到的類似的事情時,我收到了意外錯誤。 這是例子:
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)
為什么會出現這個錯誤?
謝謝。
當您使用super().__new__
時,它是object
class 的__new__
方法,它只接受一個參數 ( cls
)。 因為您還向它轉發*args, **kwargs
arguments,所以您基本上是將(cls, new=True)
發送到只需要(cls)
的方法
希望這是有道理的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.