在 ipython
我可以使用 TAB 查看对象的对象:
In [1]: import numpy as np
In [2]: np.
Display all 590 possibilities? (y or n)
np.ALLOW_THREADS np.bartlett np.errstate np.isclose np.nested_iters np.seterrcall
np.BUFSIZE np.base_repr np.euler_gamma np.iscomplex np.newaxis np.seterrobj
np.CLIP np.bench np.exp np.iscomplexobj np.newbuffer np.setxor1d
np.ComplexWarning np.binary_repr np.exp2 np.isfinite np.nextafter np.shape
np.DataSource np.bincount np.expand_dims np.isfortran np.nonzero np.shares_memory
....
在 ipython
之外是否有编程方式来执行此操作?我可以在常规 Python 脚本中打印这些对象吗?
最佳答案
dir(..)
命令可用于获取对象拥有的属性列表。例如:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> dir(np)
['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW',..., 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack', 'warnings', 'where', 'who', 'zeros', 'zeros_like']
(输出被剪切以便更容易获取和格式化)。
它返回一个字符串列表,显示对象中的内容。请注意,此函数也可用于Python 编程:例如,您可以对其进行迭代、过滤特定模式并将这些属性复制到另一个对象。例如,您可以编写一个 copy_fields
函数:
def copy_fields(frm,to):
for attr in dir(frm):
setattr(to,atr,getattr(frm,atr))
这里 getattr(..)
和 setattr(..)
是给定对象(frm
和 to
)和属性名称(attr
)的函数,分别获取和设置该属性。
我非常有信心这就是(或多或少)在 ipython
的幕后发生的事情(尽管 ipython 可能还旨在派生类型以便它可以编写括号((
) 用于函数等
最后请注意,dir(..)
不能总是报告所有属性(因为有时属性可以由函数处理,导致对象“实际上”具有无限数量的属性; 例如 BeautifulSoup
中的对象就是这种情况,如果属性不是标准化的,BeautifulSoup 会将其视为查询)。幕后dir(..)
的工作原理如下:
If the object has a method named
__dir__()
, this method will be called and must return the list of attributes. This allows objects that implement a custom__getattr__()
or__getattribute__()
function to customize the waydir()
reports their attributes.If the object does not provide
__dir__()
, the function tries its best to gather information from the object’s__dict__
attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom__getattr__()
.
关于python - 如何在 ipython 中显示对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41812447/