class MyMeta(type):
def __init__(self, *args, **kwargs):
self.__instance = None
super(MyMeta, self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super(MyMeta, self).__call__(*args, **kwargs)
return self.__instance
class MyClass(metaclass=MyMeta):
pass
m = MyClass()
m2 = MyClass()
print(m2 == m) # True
class MyClass1:
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls, *args, **kwargs)
return cls.__instance
m3 = MyClass1()
m4 = MyClass1()
print(m3 == m4) # True
m3.a = "aaa"
print(m4.a) # “aaa”
python 元类和__new__创建单例类
最新推荐文章于 2024-08-23 16:53:34 发布