【发布时间】:2018-05-06 01:18:56
【问题描述】:
在 ipython 终端中,假设我创建了一个对象,然后只需键入对象的名称并点击返回,那么查询该对象的哪些属性/方法(以及以什么顺序)以产生返回到屏幕的输出?
例如,
In [1]: from mymodule import myclass
In [2]: C = myclass()
In [3]: C # hit return
Out[3]:
查询 C 的哪些属性/方法以在 Out[3] 中生成输出?
更新:从答案(以及我发现的duplicate question 中,它表明调用了__repr__。但是,我有一个定义__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__ 方法!在我的课堂上,我有自己定义的__getattr__ 方法,这会导致问题吗?
【问题讨论】:
标签: ipython