python - 为什么应用于实例的 Python 帮助函数在某些情况下返回有关父类的页面,而在其他情况下则不返回?

标签 python types help-system

我试图了解当使用帮助函数来询问在我的代码中创建的对象时如何获得有用的结果。我对不同类别的不同行为感到困惑。

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) 产生 No Python 文档找到 'Hello World',而 help(inst2) 产生:

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 传递给 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 上的帮助。

关于python - 为什么应用于实例的 Python 帮助函数在某些情况下返回有关父类的页面,而在其他情况下则不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59431957/

相关文章:

python - python += 字符串连接是不好的做法吗?

python - 加快对 pandas 系列的异常值检查

c++ - 如何识别 LLVM/C++ 中的任何类型的指令?

delphi - 在 Delphi 中如何判断哪个菜单项是打开的?

powershell - Get-Content 中的 -raw 开关参数在 Powershell 中到底有什么作用?查找有用的文档

python - Predict_proba 不适用于我的高斯混合模型(sklearn,python)

python - 获取列的 [0, x] 元素的最小值

c - 无法获取字符串的第 n 个字符

collections - F# 中 list 和 [] 的区别