有人问如何遍历取得类的子类或实例

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

# coding:utf-8
"""
有人问如何遍历取得类的子类或实例
黄哥python远程视频培训班
https://github.com/pythonpeixun/article/blob/master/index.md
黄哥python培训试看视频播放地址
https://github.com/pythonpeixun/article/blob/master/python_shiping.md
咨询qq:1465376564
"""
import weakref


class Foo(object):
    """取得类的所有实例方法。"""

    instances = []

    def __init__(self, name=None):
        self.__class__.instances.append(weakref.proxy(self))
        self.name = name


def get_all_subclasses(cls):
        """取得类的子类,子类的子类通过递归取得"""
        all_subclasses = []

        for subclass in cls.__subclasses__():
            all_subclasses.append(subclass)
            tmp = get_all_subclasses(subclass)
            all_subclasses.extend(tmp)

        return all_subclasses


class Foo2(Foo):
    pass


class Foo3(Foo):
    pass


class Foo4(Foo2):
    pass

p1 = Foo('p1')
p2 = Foo('p2')
p3 = Foo('p3')
p4 = Foo('p4')

for instance in Foo.instances:
    print(instance.name)

print get_all_subclasses(Foo)