gpt4 book ai didi

python - 如何获得模块中类的定义?

转载 作者:太空狗 更新时间:2023-10-30 02:38:42 26 4
gpt4 key购买 nike

为什么我不能在下面的代码中从模块 collections 中获取 Callable 的定义?

如何获取模块中类的定义?谢谢。

>>> from collections import Callable
>>> inspect.getsource(Callable)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/inspect.py", line 944, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python3.5/inspect.py", line 931, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python3.5/inspect.py", line 788, in findsource
raise OSError('could not find class definition')
OSError: could not find class definition
>>> inspect.getsourcelines(Callable)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/inspect.py", line 931, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python3.5/inspect.py", line 788, in findsource
raise OSError('could not find class definition')
OSError: could not find class definition
>>> inspect.getmodule(Callable)
<module 'collections.abc' from '/usr/lib/python3.5/collections/abc.py'>
>>> inspect.getfile(Callable)
'/usr/lib/python3.5/collections/abc.py'
>>> inspect.getsourcefile(Callable)
'/usr/lib/python3.5/collections/abc.py'

最佳答案

一般来说,这很容易用 inspect.getsource 完成它接受一个模块、一个类、一个方法、一个函数、一个回溯、一个框架,或代码对象。它们所代表的源当然应该用 Python 编写,否则会引发错误。

在这种特定情况下,您只是碰巧不走运,因为 _collections_abc定义 Callable the Callable.__module__ name is callections.abc :

>>> Callable.__module__
'collections.abc'

这会关闭 getsource,因为它不会在包含 Callable 定义的 _collections_abc 中查找,而是在 collections 中查找.abc 仅从 _collections_abc 导入所有定义:

>>> print(getsource(collections.abc))
from _collections_abc import *
from _collections_abc import __all__

通常,getsource 查找源代码没有问题,例如,在其自身上:

>>> print(getsource(getsource))
def getsource(object):
"""Return the text of the source code for an object.

The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a single string. An
OSError is raised if the source code cannot be retrieved."""
lines, lnum = getsourcelines(object)
return ''.join(lines)

不过,在这种特定情况下,它确实如此(由于 Callable.__module__ 返回 collections.abc。)您可以将 __module__ 替换为'_collections_abc' 查看源代码的技巧:

>>> Callable.__module__ = '_collections_abc'
>>> src = getsource(Callable)
>>> print(src)
class Callable(metaclass=ABCMeta):

__slots__ = ()

@abstractmethod
def __call__(self, *args, **kwds):
return False

@classmethod
def __subclasshook__(cls, C):
if cls is Callable:
return _check_methods(C, "__call__")
return NotImplemented

但这并没有让我感到很舒服。

关于python - 如何获得模块中类的定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com