我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
当前回答
Python有一组强大的自省特性。
看看下面的内置函数:
(型) dir () (id) getattr () hasattr () globals () locals () callable ()
Type()和dir()分别对于检查对象的类型及其属性集特别有用。
其他回答
如果您想查看参数和方法,就像其他人指出的那样,可以使用pprint或dir()
如果您想查看内容的实际值,可以这样做
object.__dict__
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。这增加了获取对象文档、属性甚至源代码的各种快捷方式。例如,在函数后附加一个"?"将为对象提供帮助(有效地为"help(obj)"提供快捷方式),而使用两个"?" ("func??")将在可用时显示源代码。
还有很多额外的便利,如制表符补全、结果打印、结果历史记录等,这对于这种探索性编程非常方便。
对于内省的更多编程使用,基本的内置程序,如dir(), vars(), getattr等将是有用的,但值得您花时间检查inspect模块。要获取一个函数的源,使用inspect。例如,将其应用到自身:
>>> 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, '')
检查。如果处理包装或操作函数,Getargspec通常也很有用,因为它将给出函数参数的名称和默认值。
虽然其他人已经提到了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()函数。