在python中,一切皆对象,产生类的对象即为原来,借助魔法函数,元类,可以实现单例模式。
在此过程中,也可以探索基于元类的类实现过程。
class Meta_Class_Father(type):
_instance = None
def __new__(cls,*args,**kwargs):
print('=======Father Class __new__ function is called=======')
return super().__new__(cls,*args,**kwargs)
def __init__(self,*args,**kwargs):
print('=======Father Class __init__ function is called=======')
super().__init__(self)
def __call__(cls,*args,**kwargs):
print('=======Father Class __call__ function is called=======')
#super().__call__(*args,*kwargs)
if not cls._instance:
cls._instance = super().__call__(*args,*kwargs)
else:
print('the children class is already created')
return cls._instance
def __new__(cls,*args,**kwargs):
print('=======Children Class __new__ function is called=======')
#return super().__new__(cls,*args,**kwargs)
return super().__new__(cls)
def __init__(self,name,age):
print('=======Children Class __init__ function is called=======')
self.name = name
self.age = age
#super().__init__(*args,**kwargs)
super().__init__()
def __call__(cls,*args,**kwargs):
print('=======Children Class __call__ function is called=======')
super().__call__(cls,*args,**kwargs)
Meta_Test1 = Meta_Class_Children('tom',10)
Meta_Test2 = Meta_Class_Children('David',20)
print(Meta_Test1)
print(Meta_Test2)
print(Meta_Test1.name)
print(Meta_Test2.name)
运行后的结果如下:
=======Father Class __new__ function is called=======
=======Father Class __init__ function is called=======
=======Father Class __call__ function is called=======
=======Children Class __new__ function is called=======
=======Children Class __init__ function is called=======
=======Father Class __call__ function is called=======
the children class is already created
<__main__.Meta_Class_Children object at 0x0000017973DF5948>
<__main__.Meta_Class_Children object at 0x0000017973DF5948>
tom
tom