Why does a metaclass not have access to the attributes inhereited from a subclass of a class defined by the metaclass?
类
为什么元类不能访问
这是
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 | class Meta(type): def __init__(cls, name, bases, attrs): print"bases = {}".format(bases) items = {k:v for k,v in attrs.iteritems() if not k.startswith('__')} for k,v in items.iteritems(): print k, v class Foo(object): __metaclass__ = Meta hi = 1 # This prints: # bases = (<type 'object'>,) # hi 1 class Bar(Foo): pass # This prints: # bases = (<class '__main__.Foo'>,) Foo.hi #prints 1 Bar.hi #prints 1 |
正如@orlp所说,
另一种方法是使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Meta(type): def __init__(cls, name, bases, attrs): print"bases = {}".format(bases) for attr in dir(cls): if not attr.startswith('_'): print attr, getattr(cls, attr) class Foo(object): __metaclass__ = Meta hi = 1 class Bar(Foo): pass |
哪些印刷品:
1 2 3 4 | bases = (<type 'object'>,) hi 1 bases = (<class '__main__.Foo'>,) hi 1 |