如何在我的元类中获取类的父类?

时间:2014-11-29 09:37:49

标签: inheritance python-3.x metaprogramming metaclass python-datamodel

我有following script

#!/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'>)

我犯了哪个错误?

1 个答案:

答案 0 :(得分:1)

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