我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
当前回答
我很惊讶居然没人提到帮助!
In [1]: def foo():
...: "foo!"
...:
In [2]: help(foo)
Help on function foo in module __main__:
foo()
foo!
Help让您阅读文档字符串并了解类可能具有的属性,这非常有用。
其他回答
其他人已经提到了dir()内置,这听起来像是您正在寻找的,但这里有另一个很好的提示。许多库——包括大多数标准库——都是以源代码形式发布的。这意味着您可以很容易地直接阅读源代码。诀窍在于找到它;例如:
>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'
*。Pyc文件已编译,因此删除后面的'c',并在您最喜欢的编辑器或文件查看器中打开未编译的*.py文件:
/usr/lib/python2.5/string.py
我发现这对于发现从给定API引发哪些异常等事情非常有用。这种细节在Python世界中很少有良好的文档。
尝试ppretty
from ppretty import ppretty
class A(object):
s = 5
def __init__(self):
self._p = 8
@property
def foo(self):
return range(10)
print ppretty(A(), indent=' ', depth=2, width=30, seq_length=6,
show_protected=True, show_private=False, show_static=True,
show_properties=True, show_address=True)
输出:
__main__.A at 0x1debd68L (
_p = 8,
foo = [0, 1, 2, ..., 7, 8, 9],
s = 5
)
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
>>>
虽然其他人已经提到了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()函数。