我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
当前回答
如果您正在寻找一个稍微更微妙的解决方案,您可以尝试objprint。它的一个积极的方面是它可以处理嵌套对象。例如:
from objprint import objprint
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
class Player:
def __init__(self):
self.name = "Alice"
self.age = 18
self.items = ["axe", "armor"]
self.coins = {"gold": 1, "silver": 33, "bronze": 57}
self.position = Position(3, 5)
objprint(Player())
会打印出来
<Player
.name = 'Alice',
.age = 18,
.items = ['axe', 'armor'],
.coins = {'gold': 1, 'silver': 33, 'bronze': 57},
.position = <Position
.x = 3,
.y = 5
>
>
其他回答
已经有很多好的提示了,但还没有提到最短和最简单的(不一定是最好的):
object?
虽然其他人已经提到了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()查看模块的内容或对象的属性。
还有更多。
如果你对此感兴趣,可以看看objbrowser。它使用Python标准库中的inspect模块进行下面的对象内省。
如果你有兴趣查看对象myobj对应的函数的源代码,你可以输入iPython或Jupyter Notebook:
myobj ? ?
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
>>>