我开始在各种项目中使用Python进行编程(包括Django Web开发和Panda3D游戏开发)。
为了帮助我理解正在发生的事情,我想基本上“查看”Python对象以查看它们的工作方式 - 如其方法和属性。
所以说,如果我有一个Python对象,我需要什么才能打印出它的内容?这可能吗?
我开始在各种项目中使用Python进行编程(包括Django Web开发和Panda3D游戏开发)。
为了帮助我理解正在发生的事情,我想基本上“查看”Python对象以查看它们的工作方式 - 如其方法和属性。
所以说,如果我有一个Python对象,我需要什么才能打印出它的内容?这可能吗?
object.__dict__
vars(object)
是为此而设计的。 - liberforce我很惊讶还没有人提到帮助呢!
In [1]: def foo():
...: "foo!"
...:
In [2]: help(foo)
Help on function foo in module __main__:
foo()
foo!
通过 Help 命令,您可以阅读文档字符串并了解类可能具有的属性,这非常有帮助。
首先,阅读源代码。
其次,使用 dir()
函数。
func??
”)将显示源代码(如果有的话)。此外还有很多其他便利功能,如制表符补全、结果的漂亮打印、结果历史记录等,使其非常适用于这种探索性编程。dir()
、vars()
、getattr
等会很有用,但检查inspect模块也值得花费时间。要获取函数的源代码,请使用“inspect.getsource
”,例如将其应用于自身。>>> print inspect.getsource(inspect.getsource)
def getsource(object):
"""Return the text of the source code for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a single string. An
IOError is raised if the source code cannot be retrieved."""
lines, lnum = getsourcelines(object)
return string.join(lines, '')
inspect.getargspec
在处理包装或操作函数时也经常很有用,因为它会给出函数参数的名称和默认值。
试试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
)
虽然其他人已经提到了pprint
,但我想补充一些背景信息。
pprint模块提供了一种能够以可用作解释器输入的形式“漂亮打印”任意Python数据结构的功能。如果格式化的结构包括不是基本Python类型的对象,则表示可能无法加载。如果包括文件、套接字、类或实例等对象,以及许多其他无法表示为Python常量的内置对象,就可能出现这种情况。
pprint
可能会受到具有PHP背景的开发人员的高度需求,他们正在寻找var_dump()
的替代方法。
具有字典属性的对象可以使用pprint()
和vars()
混合转储,后者返回模块、类、实例等的__dict__
属性:
from pprint import pprint
pprint(vars(your_object))
因此,无需循环。
要转储包含在全局或本地作用域中的所有变量,只需使用:
pprint(globals())
pprint(locals())
locals()
函数显示在函数内定义的变量。
此外,使用相应名称作为字符串键访问函数也很有用,以及其他用途:
locals()['foo']() # foo()
globals()['foo']() # foo()
dir()
可以查看模块的内容或对象的属性。你可以在shell中使用dir()列出对象的属性:
>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
当然,还有inspect模块:http://docs.python.org/library/inspect.html#module-inspect
有一款非常酷的工具叫做objexplore
。以下是一个简单的示例,演示如何在pandas DataFrame上使用它的explore
函数。
import pandas as pd
df=pd.read_csv('https://storage.googleapis.com/download.tensorflow.org/data/heart.csv')
from objexplore import explore
explore(df)
在您的shell中将弹出以下内容: