知一的指纹

Python元类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class BaseMetaClass(type):
___sub_class = {}

def __iter__(self):
for item in BaseMetaClass.___sub_class.itervalues():
yield item

def __repr__(cls):
return cls.__name__

def __new__(mcs, name, bases, attrs):
new_cls = super(BaseMetaClass, mcs).__new__(mcs, name, bases, attrs)
if object not in bases:
BaseMetaClass.___sub_class[new_cls.__name__] = new_cls
print mcs, name, bases, attrs, new_cls
return new_cls


class NotifyManager(object):
__metaclass__ = BaseMetaClass

def __iter__(self):
yield self.__metaclass__


class TestA(NotifyManager):

@classmethod
def notify(cls):
return cls.__name__


class TestB(NotifyManager):

@classmethod
def notify(cls):
return cls.__name__
noogel wechat
文章会同步推送到公众号,欢迎关注!
如果此文章能给您带来小小的提升,不妨小额赞赏我一下,以鼓励我写出更好的文章!