Learn python with socratica [My notes] - part 6- Interactive Help

Lesson 8

课程介绍的python内容毕竟有限,所以在自学过程中你可能需要得到及时的帮助,使得自己对所要使用的方法有所了解。因此,你可以了解一下python的interactive help,学会使用它可以帮助你自学的时候获取class,function和module的信息。

Help

# To begin
dir()  # short for "directory"

['In',
 'Out',
 '_',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'get_ipython',
 'quit']

显示的是目前可以调用的内建对象。本节课以’ builtins ‘模块为例,讲述如何获得帮助。对于内建对象还不了解的同学,可以看http://blog.51cto.com/xpleaf/1764849 一文中的解释。

# get the functions in '__builtins__'
dir(__builtins__)

['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 'ChildProcessError',
 'ConnectionAbortedError',
 'ConnectionError',
 'ConnectionRefusedError',
 'ConnectionResetError',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FileExistsError',
 'FileNotFoundError',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'InterruptedError',
 'IsADirectoryError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'ModuleNotFoundError',
 'NameError',
 'None',
 'NotADirectoryError',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'PermissionError',
 'ProcessLookupError',
 'RecursionError',
 'ReferenceError',
 'ResourceWarning',
 'RuntimeError',
 'RuntimeWarning',
 'StopAsyncIteration',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'TimeoutError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'ZeroDivisionError',
 '__IPYTHON__',
 '__build_class__',
 '__debug__',
 '__doc__',
 '__import__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'display',
 'divmod',
 'dreload',
 'enumerate',
 'eval',
 'exec',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']

打印出来的是该模块所有可以调用的函数,下面举个例子看看:

# for example, let's learn about 'pow' function
help(pow)

Help on built-in function pow in module builtins:

pow(x, y, z=None, /)
    Equivalent to x**y (with two arguments) or x**y % z
     (with three arguments)

    Some types, such as ints, are able to use a more efficient algorithm 
    when invoked using the three argument form.

利用help()可以得到模块中函数的解释:

  1. 第一行,表示该函数在 builtins 模块中;
  2. 下面的部分,是解释如何使用这个函数。

在pow()函数中有三个参数,x,y,z。最终的输出为ints类型的number。
[一般包括参数、功能介绍、输入输出和详细信息。]

pow(2,10)
1024

# of course, you can also get the result by using another way in the description
2 ** 10
1024

下面我们再举个例子:hex()

help(hex)

Help on built-in function hex in module builtins:

hex(number, /)
    Return the hexadecimal representation of an integer.

    >>> hex(12648430)
    '0xc0ffee'

hex的功能就不赘述了,给定一个int类型数,返回其十六进制的转换,以string类型给出。不过,这里又一个小注意点,python自带对十六进制的解释:

hex(10)
'0xa'

0xa
10

List of modules

help('modules')

Please wait a moment while I gather a list of all available modules...
/usr/local/lib/python3.6/dist-packages/IPython/kernel/__init__.py:13: ShimWarning: The `IPython.kernel` package has been deprecated since IPython 4.0.You should import from ipykernel or jupyter_client instead.
  "You should import from ipykernel or jupyter_client instead.", ShimWarning)
Using TensorFlow backend.
/usr/local/lib/python3.6/dist-packages/nltk/twitter/__init__.py:20: UserWarning: The twython library has not been installed. Some functionality from the twitter package will not be available.
  warnings.warn("The twython library has not been installed. "
/usr/local/lib/python3.6/dist-packages/IPython/utils/traitlets.py:5: UserWarning:

IPython.utils.traitlets has moved to a top-level traitlets package.

<IPython.core.display.Javascript object>

/usr/local/lib/python3.6/dist-packages/skimage/viewer/__init__.py:6: UserWarning:

Viewer requires Qt

/usr/local/lib/python3.6/dist-packages/statsmodels/compat/pandas.py:56: FutureWarning:

The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.

/usr/lib/python3.6/pkgutil.py:107: VisibleDeprecationWarning:

zmq.eventloop.minitornado is deprecated in pyzmq 14.0 and will be removed.
    Install tornado itself to use zmq with the tornado IOLoop.

IPython             bz2                 lsb_release         selectors
PIL                 cProfile            lzma                setuptools
__future__          cachetools          macpath             shelve
_ast                calendar            macurl2path         shlex
_asyncio            certifi             mailbox             shutil
_bisect             cgi                 mailcap             signal
_blake2             cgitb               markdown            simplegeneric
_bootlocale         chardet             markupsafe          site
_bz2                chunk               marshal             sitecustomize
_codecs             cmath               math                six
_codecs_cn          cmd                 matplotlib          skimage
_codecs_hk          code                mimetypes           sklearn
_codecs_iso2022     codecs              mistune             smtpd
_codecs_jp          codeop              mmap                smtplib
_codecs_kr          collections         modulefinder        sndhdr
_codecs_tw          colorsys            mpmath              socket
_collections        compileall          msgpack             socketserver
_collections_abc    concurrent          msgpack_numpy       softwareproperties
_compat_pickle      configparser        multiprocessing     spacy
_compression        contextlib          murmurhash          spwd
_crypt              copy                nbconvert           sqlite3
_csv                copyreg             nbformat            sre_compile
_ctypes             crcmod              netrc               sre_constants
_ctypes_test        crypt               networkx            sre_parse
_curses             csv                 nis                 ssl
_curses_panel       ctypes              nltk                stat
_datetime           curses              nntplib             statistics
_dbm                cv2                 notebook            statsmodels
_dbus_bindings      cycler              ntpath              storemagic
_dbus_glib_bindings cymem               nturl2path          string
_decimal            cythonmagic         numbers             stringprep
_dummy_thread       cytoolz             numpy               struct
_elementtree        datetime            oauth2client        subprocess
_functools          dateutil            oauthlib            sunau
_hashlib            dbm                 olefile             symbol
_heapq              dbus                opcode              sympy
_imp                decimal             operator            sympyprinting
_io                 decorator           optparse            symtable
_json               defusedxml          os                  sys
_locale             difflib             ossaudiodev         sysconfig
_lsprof             dill                pandas              syslog
_lzma               dis                 pandas_gbq          tabnanny
_markupbase         distutils           pandocfilters       tarfile
_md5                doctest             parser              telnetlib
_multibytecodec     dummy_threading     past                tempfile
_multiprocessing    easy_install        pathlib             tensorboard
_opcode             email               patsy               tensorflow
_operator           encodings           pdb                 tensorflow_hub
_osx_support        entrypoints         pexpect             termcolor
_pickle             enum                pickle              terminado
_posixsubprocess    errno               pickleshare         termios
_pydecimal          faulthandler        pickletools         test
_pyio               fcntl               pip                 test_regex
_random             filecmp             pipes               testpath
_regex              fileinput           pkg_resources       tests
_regex_core         filelock            pkgutil             textwrap
_sha1               fnmatch             plac                theano
_sha256             formatter           plac_core           thinc
_sha3               fractions           plac_ext            this
_sha512             ftplib              plac_tk             threading
_signal             functools           platform            time
_sitebuiltins       future              plistlib            timeit
_socket             gast                plotly              tkinter
_sqlite3            gc                  pluggy              tlz
_sre                genericpath         poplib              token
_ssl                getopt              portpicker          tokenize
_stat               getpass             posix               toml
_string             gettext             posixpath           toolz
_strptime           gi                  pprint              tornado
_struct             glob                preshed             tqdm
_symtable           google_auth_httplib2 profile             trace
_sysconfigdata_m_linux_x86_64-linux-gnu google_auth_oauthlib prompt_toolkit      traceback
_testbuffer         googleapiclient     pstats              tracemalloc
_testcapi           grp                 psutil              traitlets
_testimportmultiple grpc                pty                 tty
_testmultiphase     gzip                ptyprocess          turtle
_thread             h5py                pwd                 types
_threading_local    hashlib             py                  typing
_tkinter            heapq               py_compile          ujson
_tracemalloc        hmac                pyasn1              unicodedata
_warnings           html                pyasn1_modules      unittest
_weakref            http                pyclbr              uritemplate
_weakrefset         httplib2            pydoc               urllib
abc                 idna                pydoc_data          urllib3
absl                imaplib             pyexpat             uu
aifc                imghdr              pygments            uuid
altair              imp                 pygtkcompat         vega_datasets
antigravity         importlib           pylab               venv
apiclient           inspect             pymc3               virtualenv
apt                 io                  pyparsing           virtualenv_support
apt_inst            ipaddress           pystache            warnings
apt_pkg             ipykernel           pytz                wave
aptsources          ipykernel_launcher  pywt                wcwidth
argparse            ipython_genutils    queue               weakref
array               itertools           quopri              webbrowser
ast                 jinja2              random              webencodings
astor               joblib              re                  werkzeug
asynchat            json                readline            wheel
asyncio             jsonschema          regex               wrapt
asyncore            jupyter             reprlib             wsgiref
atexit              jupyter_client      requests            xdrlib
audioop             jupyter_core        requests_oauthlib   xgboost
autoreload          keras               resource            xml
base64              keras_applications  rlcompleter         xmlrpc
bdb                 keras_preprocessing rmagic              xxlimited
bin                 keyword             rsa                 xxsubtype
binascii            lib2to3             runpy               yaml
binhex              libfuturize         sched               zipapp
bisect              libpasteurize       scipy               zipfile
bleach              linecache           seaborn             zipimport
bs4                 locale              secrets             zlib
builtins            logging             select              zmq

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".

此处列出的是可以调用的模块,比如要是装了numpy或者什么的,就会在这个list中。下面讲讲怎么去直接获取这些模块里的帮助信息。

# eg: math
# step 1: import
import math
# check
dir()

['In',
 'Out',
 '_',
 '_1',
 '_2',
 '_4',
 '_5',
 '_7',
 '_8',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'get_ipython',
 'math',
 'quit']

此时,math模块就加入到你的内建list,代表你可以调用它了。

dir(math)



['__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'tau',
 'trunc']

# radians
help(radians) # return the NameError

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-13-8223eb0f88be> in <module>()
----> 1 help(radians)

NameError: name 'radians' is not defined

# This is because that it is not the inner module in python
# You must use in this way

help(math.radians)

Help on built-in function radians in module math:
radians(...)
    radians(x)

    Convert angle x from degrees to radians.

从描述中可以得到,radians函数可以将给定的角度转换成π。

radians(180) # return the NameError again
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-15-165408e9dc79> in <module>()
----> 1 radians(180)

NameError: name 'radians' is not defined

math.radians(180)
3.141592653589793

因此,一定要记住,如果不是python内建模块,在调用模块函数时,前面一定要把模块名一起写在来。

Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-