请教一个问题python中单例模式和初始化函数带参数冲突吗?
import time
class po_more:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_a'):
cls._a = super().__new__(cls, *args, **kwargs)
print('11111111111')
return cls._a
def __init__(self,t) -> None:
print('111111',t)
def add(self, num):
n = 0
if n < num:
n += 1
time.sleep(1)
print(n)
if __name__ == '__main__':
a = po_more('1')
b = po_more('1')
a.add(8)
b.add(5)
上面的代码中原来是没有参数t的,当我增加参数t之后(相应的实参‘1’也删除),执行就报错,删除后就不报错,想知道为什么?
执行报错信息:
Traceback (most recent call last):
File "f:\mywscode\py2\po.py", line 24, in <module>
a = po_more('1')
File "f:\mywscode\py2\po.py", line 7, in __new__
cls._a = super().__new__(cls, *args, **kwargs)
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
想要正常的添加参数,要怎么操作?请不吝赐教!