Inconsistency in python help('string') versus help(list)?

后端 未结 5 748
旧时难觅i
旧时难觅i 2021-01-25 05:58

When I type help(\'string\') in the python interpreter I get information about the string class. There,upper() is indicated as a function. Yet I can on

相关标签:
5条回答
  • 2021-01-25 06:22

    There's nothing wrong with what you see.

    >>> help('string')
    

    Will show you the string module documentation. And it looks like there's an upper function inside:

    >>> import string
    >>> string.upper('hello')
    'hello'
    

    I'd say that this upper is the same that is called if you do:

    >>> 'hello'.upper()
    

    But I'm not sure.

    Notice that a string '' is a str type not a string type. This means that you're probably looking for:

    >>> help('str')
    

    And here you'll see too the str.upper method.

    0 讨论(0)
  • 2021-01-25 06:26

    This is because 'string' is a string. So is 'list'

    To get a similar result for lists, try help([])

    0 讨论(0)
  • 2021-01-25 06:30

    You are creating an instance of that object and then calling help on that instance.

    So these all work:

    help(1)
    help({})
    help([])
    help('')
    help(dir)
    help(help)
    

    Help grabs the docstring for that instance, and gives it back to you. When you create your own objects, you can put in useful docstrings or whatever you want.

    0 讨论(0)
  • 2021-01-25 06:31

    You mean to do help('str'), not help('string'). str is a type, string is a module providing functions for working with strings.

    0 讨论(0)
  • 2021-01-25 06:39

    When you searched for help('string'), you were looking for the docstrings of the string module. If you do help(str) or help('str') you'll get the docstrings of the str type, and here upper appears as a method!

    As you can see here, the function upper from the string module is actually a function and not a method:

    >>> upper('hi')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'upper' is not defined
    >>> 'hi'.upper() # method from the str type
    'HI'
    >>> from string import upper
    >>> upper('hi') # function from the string module
    'HI'
    
    0 讨论(0)
提交回复
热议问题