python 有人问如何遍历取得类的子类或实例
当前位置:以往代写 > Python教程 >python 有人问如何遍历取得类的子类或实例
2019-06-14

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

python 有人问如何遍历取得类的子类或实例
python"># 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)

标签:python

    关键字:

在线提交作业