如何检索对象的源代码?

时间:2017-10-17 10:12:37

标签: python-3.x

假设一个类

class Book(object):
    def __init__(self, title, author):
        self.title = title
        self.author = author
    def get_entry(self):
        return self.__dict__

创建一个实例:

>>> book = Book('Think Python', 'Allen')
>>> vars(book)
{'title': 'Think Python', 'author': 'Allen'}

我进一步检索对象书的陈述。 我想要的输出是{'title': 'Think Python', 'author': 'Allen','get_entry':statements}

所以我导入inspect以获取实时对象的信息

>>> import inspect
>>> inspect.getsource(book)

错误报告

TypeError: <__main__.Book object at 0x10f3a0908> is not a module, class, method, function, traceback, frame, or code object

但是,python文档指定&#39;返回对象的源代码文本。参数可以是模块,类,方法,函数,回溯,框架或代码对象。源代码作为单个字符串返回。如果无法检索源代码,则会引发OSError。&#39; 29.12. inspect — Inspect live objects — Python 3.6.3 documentation 这里有什么问题?

1 个答案:

答案 0 :(得分:1)

getsource函数适用于类,而不适用于类的实例。所以,你必须按如下方式传递它:

inspect.getsource(Book) # Book is the class, defined by 'class Book:'

而不是:

inspect.getsource(book) # where book is an Instance of the Book class.

该类存储代码蓝图,该实例只是该蓝图的一个版本,具有自己的值。因此,你需要通过课程。