我试图了解如何在 Python 中创建单例类。以下是我如何尝试
class Singleton(object):
_instance = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_)
return class_._instance
class MyClass(Singleton):
num_of_instances = 0
def __init__(self, real = 5, imaginary = 6):
self.real = real
self.imaginary = imaginary
MyClass.num_of_instances += 1
a = MyClass(10, 20)
print(a.real)
print(a.imaginary)
b = MyClass()
print(MyClass.num_of_instances) # 2
理想情况下使用对象实例__new__()调用__init__(),但在上述情况下,当我尝试创建第二个对象时b,__new__不会被调用,因为实例MyClass已经存在那么为什么打印语句打印num_of_instancesprint 2?
相关分类