如何获取模块定义的所有子类(特定类)?

时间:2013-09-24 09:24:28

标签: python module subclass

给定模块module和类MyClass,如何获取MyClass中定义的module的所有子类的列表?

4 个答案:

答案 0 :(得分:6)

您可以使用inspect.getmembers()。假设你有mymodule.py

class A(object):
    pass


class B(A):
    pass


class C(A):
    pass

以下是如何获取A的所有子类:

import inspect
import mymodule
from mymodule import A

def is_subclass(o):
    return inspect.isclass(o) and issubclass(o, A)


print inspect.getmembers(mymodule, predicate=is_subclass)

或简称lambda形式:

print inspect.getmembers(mymodule,  
                         predicate=lambda o: inspect.isclass(o) and \
                                             issubclass(o, A))

答案 1 :(得分:1)

classes = ()
for name in dir(module):
    obj = getattr(module, name)
    try:
        # obj.__mro__ raises AttributeError on non-class
        if MyClass in obj.__mro__ and obj is not MyClass:
            classes += (obj,)
        #else:
        #    print name, "is no subclass of", MyClass
    except AttributeError:
        #print name, "is no class"
        pass  # you might of course use an if hasattr(obj, '__mro__') instead

不漂亮,但有效。欢迎替代方案......

答案 2 :(得分:1)

我的尝试:

>>> def f(module):
...     things = [getattr(module, x) for x in dir(module)]
...     return [x for x in things if type(x) == type]
...
>>> import datetime
>>> f(datetime)
[<type 'datetime.date'>, <type 'datetime.datetime'>, <type 'datetime.time'>, <type 'datetime.timedelta'>, <type 'datetime.tzinfo'>]

答案 3 :(得分:0)

也许尝试pyclbr模块 - Python类浏览器支持

http://pymotw.com/2/pyclbr/