给定一个模块module
和一个类MyClass
,如何获取MyClass
定义的所有子类的列表module
?
问问题
2533 次
4 回答
8
您可以使用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))
于 2013-09-24T09:35:03.923 回答
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'>]
于 2013-09-24T09:44:03.200 回答
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
不漂亮,但有效。替代品是受欢迎的,但...
于 2013-09-24T09:24:27.943 回答
0
也许试试 pyclbr 模块——Python 类浏览器支持
于 2013-09-24T09:49:29.220 回答