1. 元类
参考http://python.jobbole.com/88795/,个人觉得讲解的很透彻。
元类是一个类的类,该类是它的元类的一个实例。类的定义由它的元类决定,所以我们用类A创建一个类时,Python通过调用A=type(name, bases, dict)创建它,name--类的名字,bases--基类,dict--属性变量。如下两段代码,其实作用一样。
# 创建一个Hello类,拥有属性say_hello
class Hello():
def say_hello(self, name='world'):
print('Hello, %s.' % name)
# 从Hello类创建一个实例hello
hello = Hello()
# 使用hello调用方法say_hello
hello.say_hello()
def fn(self, name='world'): # 假如我们有一个函数叫fn
print('Hello, %s.' % name)
Hello = type('Hello', (object,), dict(say_hello=fn)) # 通过type创建Hello class
# 从Hello类创建一个实例hello
hello = Hello()
# 使用hello调用方法say_hello
hello.say_hello()
Python3.5中的一个示例元类的实现:
class MyInt(type):
def __call__(cls, *args, **kwds):
print('***** Here is My int *****', args)
print('Now do whatever you want with these objects...')
return type.__call__(cls, *args, **kwds)
class int(metaclass=MyInt):
def __init__(self, x, y):
self.x = x
self.y = y
i = int(3, 5)
以上代码说明,对于已存在的类来说,当需要创建对象时,将调用Python的特殊方法__call__,意味着现在元类控制着对象的实例化。
2. 基于元类实现单例
以上思路说明元类对类创建和对象实例化有更多的控制权,所以可以用于创建单例。以下代码为单例的元类实现。
class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Logger(metaclass=MetaSingleton):
pass
if __name__ == '__main__':
logger1 = Logger()
logger2 =Logger()
print(logger1)
print(logger2) # same address