layout: post date: 2017-06-15 10:25:16 +0800
a-primer-on-python-metaclasses
http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example
假如你想创建一个类(注意是类,不是类的实例),那么你可以使用__mateclass__
属性来告诉这个类怎么来构造。
class Interface(object):
__metaclass__ = InterfaceMeta
file = 'tmp.txt'
print(Interface.class_id)
print(Interface.file)
__metaclass__
by defining the __metaclass__
attribute of the class, we've told the class that it should be constructed using InterfaceMeta
rather than using type
. To make this more definite, observe that the type of Interface is now InterfaceMeta:
type(Interface)
__main__.InterfaceMeta
classes are objects, and they are object of type type
type(name, bases, dict) -> a new type
type(name, bases, dct)
Now things get really fun. Just as we can inherit from and extend a class we've created, we can also inherit from and extend the type
metaclass, and create custom behavior in our metaclass.
9.13 using a metaclass to control instance creation
Using a metaclass to implement various instance create pattern can offer be a much elegant approach than other solutions not invoving metaclasses.
singleton(单例模式) 或者不允许实例化的类
Django meta