我有以下脚本:
#!/usr/bin/python3
class MyMeta(type):
def __new__(mcs, name, bases, dct):
print(name + " " + str(bases))
return super(MyMeta, mcs).__new__(mcs, name, bases, dct)
class A(metaclass=MyMeta):
def foo(self):
pass
class B(A):
pass
class C(B):
def foo(self):
pass
def main():
pass
if __name__ == "__main__":
main()
我得到以下输出:
A ()
B (<class '__main__.A'>,)
C (<class '__main__.B'>,)
但我期待它:
A ()
B (<class '__main__.A'>,)
C (<class '__main__.B'>, <class '__main__.A'>)
我哪里犯了错误?
bases
类定义中列出的参数列表基类。
似乎你想要class.mro
:
class MyMeta(type):
def __new__(mcs, name, bases, dct):
ret = super(MyMeta, mcs).__new__(mcs, name, bases, dct)
print(name + " " + str(ret.mro()[1:-1]))
return ret