我试图了解当使用帮助函数来询问在我的代码中创建的对象时如何获得有用的结果。我对不同班级的不同行为感到困惑。
Cls1 = type( 'FirstClass', (str,), {'__doc__':'My new class'})
inst1 = Cls1('Hello World')
Cls2 = type( 'SecondClass', (object,), {'__doc__':'My second new class'})
inst2 = Cls2( )
help(inst1)
yields No Python documentation found for 'Hello World'
, while help(inst2)
yields:
Help on SecondClass in module __main__ object:
class SecondClass(builtins.object)
| My second new class
|
...
我想创建一个基于str
并能够显示有用的消息help
功能:有没有一种简单的方法可以实现这一点?
如果你想创建一个子类str
并显示提示help
内置的,您可以使用文档字符串。例如下面的子类
class NewString(str):
"""This is a brand new implementation of string type"""
def test_method(self):
"""This is a test method in the new implementation"""
pass
有以下输出help(NewString)
class NewString(builtins.str)
| This is a brand new implementation of string type
|
| Method resolution order:
| NewString
| builtins.str
| builtins.object
|
| Methods defined here:
|
| test_method(self)
| This is a test method in the new implementation
...
但对于字符串的所有实例help
方法不会有用。
它失败的原因是当通过str
to help
内置它被视为函数的名称,并且显然没有名为的函数Hello World
它显示一个错误。
运行以下命令help('help')
将输出:
Help on _Helper in module _sitebuiltins object:
help = class _Helper(builtins.object)
| Define the builtin 'help'.
|
| This is a wrapper around pydoc.help that provides a helpful message
| when 'help' is typed at the Python interactive prompt.
|
| Calling help() at the Python prompt starts an interactive help session.
| Calling help(thing) prints help for the python object 'thing'.
...
这是帮助help
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)