我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。

为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。

假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?


当前回答

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和dir一起工作效果很好

有一个很酷的工具叫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中弹出以下内容:

其他人已经提到了dir()内置,这听起来像是您正在寻找的,但这里有另一个很好的提示。许多库——包括大多数标准库——都是以源代码形式发布的。这意味着您可以很容易地直接阅读源代码。诀窍在于找到它;例如:

>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'

*。Pyc文件已编译,因此删除后面的'c',并在您最喜欢的编辑器或文件查看器中打开未编译的*.py文件:

/usr/lib/python2.5/string.py

我发现这对于发现从给定API引发哪些异常等事情非常有用。这种细节在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?