例如:
class Meta(type):
def __new__(cls, name, parents, attrs):
new_attrs={}
for k,v in attrs.items():
# Here attrs only has methods defined in "name", this is not I want.
print(k,v)
new_attrs[k] = v
return type.__new__(cls, name, parents, new_attrs)
class meta(metaclass=Meta):
pass
class a(object):
def a1(self):
return self.a2()
def a2(self):
print('a2 voked')
class b(a):
def b1(self):
return self.b2()
def b2(self):
return self.a1()
class c(b):
def c1(self):
return self.b1()
class d(c,meta):
def d1(self):
return self.c1()
x=d()
x.d1()
结果是:
>>>
__qualname__ meta
__module__ __main__
__qualname__ d
d1 <function d.d1 at 0x0000000002A7B950>
__module__ __main__
a2 voked
可以看到,在Meta
的__new__
中,除了特殊的方法,只有d1
是可以访问的。但是我也想获得它所有父类的方法(即 a1 a2 b1 b2 和 c1 对象),这样我就可以在类 d
通过元类创建时做一些有用的事情,比如添加一个装饰器到它的所有方法。那怎么办?
我知道一个类似的方法来获得它,但它有点复杂,事实上,它是在类 d
创建之后。:
import inspect
class Print(object):
@classmethod
def printize(cls,):
for name,attr in inspect.getmembers(cls):
# here all methods are accessible
# you can do something like:
# setattr(cls,name, f(attr))
class d(c,Print):
def d1(self):
return self.c1()
d.printize()
x=d()
p = type(x)
while p != object:
print(p.__bases__)
p = p.__bases__[0]
给予:
(<class '__main__.c'>, <class '__main__.meta'>)
(<class '__main__.b'>,)
(<class '__main__.a'>,)
(<class 'object'>,)
或者你可以这样做:
import inspect
print(inspect.getmro(type(x)))
获取:
(<class '__main__.d'>, <class '__main__.c'>, <class '__main__.b'>,
<class '__main__.a'>, <class '__main__.meta'>, <class 'object'>)
我是一名优秀的程序员,十分优秀!