我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。
为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。
假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?
当前回答
检查代码的两个好工具是:
IPython。一个允许你使用制表符完成检查的python终端。 使用PyDev插件的Eclipse。它有一个优秀的调试器,允许您在给定的位置中断,并通过浏览所有变量作为树来检查对象。您甚至可以使用嵌入式终端在该位置尝试编码或键入对象并按'。,让它为你提供代码提示。
其他回答
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
>>>
"""Visit http://diveintopython.net/"""
__author__ = "Mark Pilgrim (mark@diveintopython.org)"
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList])
if __name__ == "__main__":
print help.__doc__
在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"}
有一个很酷的工具叫objexplore。下面是一个简单的例子,关于如何在pandas数据框架上使用它的探索功能。
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中弹出以下内容:
此外,如果您想查看列表和字典内部,可以使用pprint()