zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python __subclasses__() 函数获取类的所有子类

Python 函数 获取 所有 __ 子类
2023-09-11 14:14:44 时间

测试: 

class A(object):
    def __init_(self, a, b):
        self.a = a
        self.b = b

    def add(self, a, b):
        return a+b

    def sub(self, a, b):
        return a-b


class B(A):
    def funb(self):
        print "Class B"

class C(A):
    def func(self):
        print "Class C"


for sc in A.__subclasses__():
    print sc.__name__

结果:

B
C

 

源码实例:

logger.info('Starting client.')

        self.dispatcher_greenlets = []

        for _, entry in self.config['baits'].items():
            for b in clientbase.ClientBase.__subclasses__():
                bait_name = b.__name__.lower()
                # if the bait has a entry in the config we consider the bait enabled
                #如果诱饵在配置中有一个条目,我们认为诱饵已启用
                if bait_name in entry:
                    bait_options = entry[bait_name]
                    dispatcher = BaitDispatcher(b, bait_options)
                    dispatcher.start()
                    self.dispatcher_greenlets.append(dispatcher)
                    logger.info('Adding {0} bait'.format(bait_name))
                    logger.debug('Bait added with options: {0}'.format(bait_options))

        gevent.joinall(self.dispatcher_greenlets)