在ipython终端中,假设我创建了一个对象,然后只需键入对象的名称并点击返回,查询该对象的哪些属性/方法(以及以何种顺序)以生成返回的输出到屏幕?
如,
In [1]: from mymodule import myclass
In [2]: C = myclass()
In [3]: C # hit return
Out[3]:
在Out[3]
?
更新:从答案(以及我找到的duplicate question开始,它显示__repr__
已被调用。但是,我有一个定义{{1}的类,但它似乎没有被使用,我得到以下追溯错误:
__repr__
最终它会尝试使用/usr/local/lib/python2.7/dist-packages/IPython/core/displayhook.pyc in __call__(self, result)
244 self.start_displayhook()
245 self.write_output_prompt()
--> 246 format_dict, md_dict = self.compute_format_data(result)
247 self.update_user_ns(result)
248 self.fill_exec_result(result)
/usr/local/lib/python2.7/dist-packages/IPython/core/displayhook.pyc in compute_format_data(self, result)
148
149 """
--> 150 return self.shell.display_formatter.format(result)
151
152 # This can be set to True by the write_output_prompt method in a subclass
/usr/local/lib/python2.7/dist-packages/IPython/core/formatters.pyc in format(self, obj, include, exclude)
150 return {}, {}
151
--> 152 format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude)
153
154 if format_dict or md_dict:
<decorator-gen-12> in __call__(self, obj, include, exclude)
/usr/local/lib/python2.7/dist-packages/IPython/core/formatters.pyc in catch_format_error(method, self, *args, **kwargs)
215 """show traceback on failed format call"""
216 try:
--> 217 r = method(self, *args, **kwargs)
218 except NotImplementedError:
219 # don't warn on NotImplementedErrors
/usr/local/lib/python2.7/dist-packages/IPython/core/formatters.pyc in __call__(self, obj, include, exclude)
962 return printer(obj)
963 # Finally look for special method names
--> 964 method = get_real_method(obj, self.print_method)
965
966 if method is not None:
/usr/local/lib/python2.7/dist-packages/IPython/utils/dir2.pyc in get_real_method(obj, name)
63
64 try:
---> 65 canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
66 except Exception:
67 return None
方法!在我的课堂上,我有自己定义的__getattr__
方法,这会导致问题吗?
答案 0 :(得分:0)
作为另一个答案,例如对this question的回答,状态通常会调用__repr__
方法。
但是,ipython搜索格式化输出时要使用的__repr__
方法的其他特殊版本,例如,请参阅此注释到ipython的format
方法DisplayFormatter
类:
If an object implement `_repr_mimebundle_` as well as various
`_repr_*_`, the data returned by `_repr_mimebundle_` will take
precedence and the corresponding `_repr_*_` for this mimetype will
not be called.
格式化程序函数因此使用get_real_method()
函数检查特定方法是否存在(请参阅here),该函数使用不应存在的虚拟方法名称调用getattr
。在我的情况下,我已经定义了我的类有自己的__getattr__
方法(这是我的问题出现的地方),它使用了hasattr
函数。由于hasattr
讨论here的问题,这会导致问题,在我的情况下意味着卡在__getattr__
函数中。因此,如果您定义自己的__getattr__
函数,道德就会非常小心,因为它会产生意想不到的后果!