我有一个容器类(从列表中继承)我已经覆盖了 geattr 方法;
def __getattr__(self, name):
def _multiplexed(*args, **kwargs):
return [getattr(R, name)(*args, **kwargs) for R in self]
return _multiplexed
麻烦的是,现在我无法向Python请求有关我的对象的帮助。当我请求帮助时,我得到(从iPython追溯)下面复制的错误。
所以问题是:如何覆盖 getattr 而不会失去我的求助能力?
谢谢, 杰里米
help(Collect)
/home/jlconlin/CustomPython/trunk/Collect.py in <module>()
----> 1
2
3
4
5
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc in __call__(self, *args, **kwds)
455 def __call__(self, *args, **kwds):
456 import pydoc
--> 457 return pydoc.help(*args, **kwds)
458
459 def sethelper():
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pydoc.pyc in __call__(self, request)
1721 def __call__(self, request=None):
1722 if request is not None:
-> 1723 self.help(request)
1724 else:
1725 self.intro()
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pydoc.pyc in help(self, request)
1768 elif request: doc(request, 'Help on %s:')
1769 elif isinstance(request, Helper): self()
-> 1770 else: doc(request, 'Help on %s:')
1771 self.output.write('\n')
1772
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pydoc.pyc in doc(thing, title, forceload)
1506 """Display text documentation, given an object or a path to an object."""
1507 try:
-> 1508 pager(render_doc(thing, title, forceload))
1509 except (ImportError, ErrorDuringImport), value:
1510 print value
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pydoc.pyc in render_doc(thing, title, forceload)
1483 desc = describe(object)
1484 module = inspect.getmodule(object)
-> 1485 if name and '.' in name:
1486 desc += ' in ' + name[:name.rfind('.')]
1487 elif module and module is not object:
TypeError: argument of type 'function' is not iterable
答案 0 :(得分:1)
查看pydoc源代码,罪魁祸首是:
getattr(thing, '__name__', None)
尝试查找thing.__name__
,如果失败,则返回None。除了你的情况,它不会失败;它会从__getattr__
返回一个值。
如果你要覆盖__getattr__
,那么特殊情况下所有特殊属性都是个好主意。类似的东西:
if name.startswith("__"):
raise AttributeError
这可以确保如果您的类没有特定的特殊属性(在本例中为__name__
),则查找它将失败,而不是产生意外值。