python中metaclass的工作原理

class TMetaclass(type):
	def __new__(cls, name, bases, attrs):
		print(cls, name, bases, attrs)
		return type.__new__(cls, name, bases, attrs)

# class T(dict, metaclass=TMetaclass):
# 	def __init__(self, **kw):
# 		super(T, self).__init__(**kw)
class T(dict, metaclass=TMetaclass):
	pass

class Test(T):
	pass

class Test1(Test):
	pass


a = Test1()

输出:

<class '__main__.TMetaclass'> T (<class 'dict'>,) {'__module__': '__main__', '__qualname__': 'T'}
<class '__main__.TMetaclass'> Test (<class '__main__.T'>,) {'__module__': '__main__', '__qualname__': 'Test'}
<class '__main__.TMetaclass'> Test1 (<class '__main__.Test'>,) {'__module__': '__main__', '__qualname__': 'Test1'}
[Finished in 0.1s]
posted @ 2017-08-04 22:04  busui  阅读(501)  评论(0编辑  收藏  举报