Python 3.x 如何检索对象的源代码?
假设一节课Python 3.x 如何检索对象的源代码?,python-3.x,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') >>> var
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'}
我进一步检索objectbook的语句。
我想要的输出是{'title':'thinkpython','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
TypeError:不是模块、类、方法、函数、回溯、帧或代码对象
但是,python文档指定“返回对象的源代码文本”。参数可以是模块、类、方法、函数、回溯、帧或代码对象。源代码作为单个字符串返回。如果无法检索源代码,将引发操作错误。”
这里怎么了?函数使用类,而不是类的实例。因此,您必须通过以下步骤:
inspect.getsource(Book) # Book is the class, defined by 'class Book:'
而不是:
inspect.getsource(book) # where book is an Instance of the Book class.
该类存储代码蓝图,而实例只是该蓝图的一个版本,具有自己的值。因此,您需要传递类。您需要传递
getsource
类本身,而不是实例<代码>检查。getsource(Book)可以工作。