我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
当前回答
如果你有兴趣查看对象myobj对应的函数的源代码,你可以输入iPython或Jupyter Notebook:
myobj ? ?
其他回答
在Python 3.8中,你可以使用__dict__. __dict__来打印对象的内容。例如,
class Person():
pass
person = Person()
## set attributes
person.first = 'Oyinda'
person.last = 'David'
## to see the content of the object
print(person.__dict__)
{"first": "Oyinda", "last": "David"}
If you want to look inside a live object, then python's inspect module is a good answer. In general, it works for getting the source code of functions that are defined in a source file somewhere on disk. If you want to get the source of live functions and lambdas that were defined in the interpreter, you can use dill.source.getsource from dill. It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code.
>>> from dill.source import getsource
>>>
>>> def add(x,y):
... return x+y
...
>>> squared = lambda x:x**2
>>>
>>> print getsource(add)
def add(x,y):
return x+y
>>> print getsource(squared)
squared = lambda x:x**2
>>>
>>> class Foo(object):
... def bar(self, x):
... return x*x+x
...
>>> f = Foo()
>>>
>>> print getsource(f.bar)
def bar(self, x):
return x*x+x
>>>
检查代码的两个好工具是:
IPython。一个允许你使用制表符完成检查的python终端。 使用PyDev插件的Eclipse。它有一个优秀的调试器,允许您在给定的位置中断,并通过浏览所有变量作为树来检查对象。您甚至可以使用嵌入式终端在该位置尝试编码或键入对象并按'。,让它为你提供代码提示。
虽然其他人已经提到了pprint,但我想添加一些上下文。
pprint模块提供了任意“漂亮打印”的功能 形式的Python数据结构,该形式可用作 翻译。如果格式化的结构包含的对象不是 基本的Python类型,表示可能是不可加载的。这 如果对象,如文件,套接字,类,或 实例包括在内,以及许多其他内置对象 不能表示为Python常量。
对于具有PHP背景、正在寻找var_dump()替代品的开发人员来说,pprint可能非常需要。
带有dict属性的对象可以使用pprint()和vars()混合转储,它会为模块、类、实例等返回__dict__属性:
from pprint import pprint
pprint(vars(your_object))
所以,不需要循环。
要转储包含在全局或局部作用域中的所有变量,只需使用:
pprint(globals())
pprint(locals())
Locals()显示函数中定义的变量。 在其他用法中,将函数的对应名称作为字符串键访问也很有用:
locals()['foo']() # foo()
globals()['foo']() # foo()
类似地,使用dir()查看模块的内容或对象的属性。
还有更多。
首先,阅读原文。
其次,使用dir()函数。