这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
当前回答
我没有测试过性能,但我相信这是在Python中以列表形式枚举任何对象的属性/属性/键的最快方法。
# If core==False, ignore __k__ entries
def obj_props(obj, core=False) -> list:
assert not obj is None, f"obj must not be null (None)"
_props = []
_use_dir=False
def _add(p):
if not core and p.find('__') == 0: return
_props.append(p)
if hasattr(obj, '__dict__'):
for p in obj.__dict__.keys(): _add(p)
elif hasattr(obj, '__slots__'):
for p in obj.__slots__: _add(p)
elif hasattr(obj, 'keys'):
try:
for p in obj.keys(): _add(p)
except Exception as ex:
_props = []
_use_dir = True
else:
_use_dir = True
if _use_dir:
# fall back to slow and steady
for p in dir(obj):
if not core and p.find('__') == 0: continue
v = getattr(obj, p)
v_t = type(v).__name__
if v_t in ('function', 'method', 'builtin_function_or_method', 'method-wrapper'): continue
_props.append(p)
return _props
上面应该适用于常规的python对象(使用__dict__),使用插槽的对象(__slots__),甚至适用于像对象一样的字典。
大多数其他示例使用dir(obj),它将枚举对象的所有方法和属性,如果您只需要它的属性,则会对性能造成影响。
其他回答
尝试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(), show_protected=True, show_static=True, show_properties=True)
输出:
__main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5)
转储myObject:
from bson import json_util
import json
print(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))
我尝试了vars()和dir();都没有达到我的期望。Vars()不起作用,因为对象没有__dict__(异常。vars()参数必须具有__dict__属性)。dir()不是我要找的:它只是一个字段名称的列表,没有给出值或对象结构。
我认为json.dumps()将适用于大多数对象,没有default=json_util.default,但我在对象中有一个datetime字段,因此标准json序列化器失败。参见如何克服“约会时间”。datetime不是JSON序列化”在python?
从答案中,可以稍微修改一下,只得到一个对象的“Attributes”,如下所示:
def getAttributes(obj):
from pprint import pprint
from inspect import getmembers
from types import FunctionType
def attributes(obj):
disallowed_names = {
name for name, value in getmembers(type(obj))
if isinstance(value, FunctionType)}
return {
name for name in dir(obj)
if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}
pprint(attributes(obj))
在临时添加此函数时非常有用,并且可以在不修改现有源代码的情况下删除此函数
你需要vars()和pprint()的混合:
from pprint import pprint
pprint(vars(your_object))
你可以使用"dir()"函数来做到这一点。
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>
另一个有用的功能是帮助。
>>> help(sys)
Help on built-in module sys:
NAME
sys
FILE
(built-in)
MODULE DOCS
http://www.python.org/doc/current/lib/module-sys.html
DESCRIPTION
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
argv -- command line arguments; argv[0] is the script pathname if known