Python Singleton模式

时间:2021-07-17 11:24:13

注意:在重写__new__方法时,object.__new__(cls)不能传参数

#!/usr/bin/env python
# -*- coding: utf-8 -*- class Singleton():
__instance = False
def __init__(self, name, age):
self.name = name
self.age = age def __new__(cls, *args, **kwargs):
if not Singleton.__instance:
Singleton.__instance = object.__new__(cls) #此处不能添加参数
return Singleton.__instance s = Singleton('hello', 18)