Python about the metaclass

花了好多天去理解unittest.main()和Base.metadata.create_all()的实现方式,如何在不实例化的情况下知道子类的信息?

以下为实验代码,详细参考《Python Cookbook(第3版)中文版》

class Metaclass(type):
    childs = []
    def __init__(self, clsname, bases, clsdict):
        super().__init__(clsname, bases, clsdict)
        self.childs.append(clsname)

class Base(metaclass=Metaclass):
    pass


class Tree1(Base):
    pass

class Tree2(Base):
    pass

if __name__ == '__main__':
    for c in Base.childs:
        print(c)

输出结果:

Base
Tree1
Tree2

Leave a Reply

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.