给定模块module
和类MyClass
,如何获取MyClass
中定义的module
的所有子类的列表?
答案 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类浏览器支持