new 方法实现单列模式思考
class Single:
_single = None
_single_only = None
def __init__(self, value):
self.v = value
print(self.v)
def __new__(cls, *args, **kwargs):
if Single._single:
return Single._single
else:
Single._single = super(Single, cls).__new__(cls, *args, **kwargs)
print("只执行一次")
return Single._single
s2 = Single(2)
#结果报错
Single._single = super(Single, cls).__new__(cls, *args, **kwargs)
TypeError: object() takes no parameters
报错显示 基类 object() 不接受额外参数
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
.......
def __new__(cls, *args, **kwargs):
if Single._single:
return Single._single
else:
Single._single = super(Single, cls).__new__(cls) #这样继承就好了
print("只执行一次")
return Single._single