本文介绍了为什么在某些情况下,应用于实例的Python帮助功能会返回有关父类的页面,而在其他情况下却不会返回该页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解当使用help函数询问在我的代码中创建的对象时如何获得有用的结果.我为不同的班级的不同行为感到困惑.

I'm trying to understand how to get useful results when the help function is used to interrogate objects created in my code. I'm puzzled by different behavior for different classes.

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 documentation found for 'Hello World',而help(inst2)产生:

Help on SecondClass in module __main__ object:

class SecondClass(builtins.object)
 |  My second new class
 |  
...

我想创建一个基于str的类,并能够通过help函数显示有用的消息:是否有实现此目的的简单方法?

I would like to create a class based on str and be able to have useful messages displayed by the help function: is there a simple way of achieving this?

推荐答案

如果要创建str的子类并使用内置的help显示提示,则可以使用文档字符串.例如以下子类

If you want to create a subclass of str and show the hints with help built-in, you can use docstrings. For instance the following subclass

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方法将无用.

But as for all instances of string the help method will not be useful.

之所以失败,是因为将str传递给help内置组件时,它将被视为函数的名称,并且显然没有名为Hello World的函数会显示错误.

The reason it fails is that when passing a str to help build-in it is treated as the name of a function, and as there obviously is not a function named Hello World it shows an error.

运行以下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帮助功能会返回有关父类的页面,而在其他情况下却不会返回该页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 00:14