初步认知
深刻理解Python中的元类(metaclass)
python当中metaclass探讨
类和元类中的 __new__ , __init__, __call__ 调用顺序
见栗子:
#!/usr/bin/env python
#-*-coding:utf-8-*-
class Meta_A(type):
def __new__(cls, name, bases, attrs):
print("Meta: __new__")
return super(Meta_A,cls).__new__(cls,name,bases,attrs)
def __init__(self, *args, **kwargs):
print("Meta: __init__")
super(Meta_A, self).__init__(*args,**kwargs)
def __call__(self,*args,**kwargs):
print("Meta: __call__")
return super(Meta_A, self).__call__(*args,**kwargs)
class A(metaclass=Meta_A):
def __new__(cls, *args, **kwargs):
print('A: __new__')
return super(A, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print('A: __init__')
def __call__(self, *args, **kwargs):
print('A: __call__')
if __name__ == "__main__":
a = A()
a()
its output
Meta: __new__
Meta: __init__
Meta: __call__
A: __new__
A: __init__
A: __call__
正如 a()会调用class A中的 __call__() 方法一样, A() 也将调用元类 Meta_A 中的 __call__() 方法,然后才是回到原 class A中并调用 __new__(), __init__().
单例模式
- 1 __new__() 方法
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls,"_instance"):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
if __name__ == '__main__':
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
不能用 __init__() 方法,那是因为类的实例对象在 __new__() 中创建,在 __init__() 只是初始化实例对象而已。
- 2 元类中的 __call__() / __init__()
class Singleton(type):
def __init__(self, *args, **kwargs):
self.__instance = None
super(Singleton,self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super(Singleton,self).__call__(*args, **kwargs)
return self.__instance
class Foo(metaclass=Singleton):
pass
if __name__ == '__main__':
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True
- 3 元类中的 __call__() / __new__()
class Singleton(type):
def __new__(cls, name,bases,attrs):
attrs["_instance"] = None
return super(Singleton,cls).__new__(cls,name,bases,attrs)
def __call__(self, *args, **kwargs):
if self._instance is None:
self._instance = super(Singleton,self).__call__(*args, **kwargs)
return self._instance
class Foo(metaclass=Singleton):
pass
if __name__ == '__main__':
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True