博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过help()自学Python
阅读量:6895 次
发布时间:2019-06-27

本文共 11578 字,大约阅读时间需要 38 分钟。

hot3.png

pyhton中   

通过如下链接学习相关基本内容,包括:基本数据类型、控制流、数据结构、模块、输入输出、异常捕获、类。

http://docs.python.org/2.7/tutorial/


1.help命令

help(类名)查看类中所有详细的功能

help(类名.函数名)查看类中某函数方法的详细内容

breath@ubuntu:~$ bpythonbpython version 0.15 on top of Python 2.7.6 /usr/bin/python2.7>>> helpType help() for interactive help, or help(object) for help about object.>>> help()Welcome to Python 2.7!  This is the online help utility.If this is your first time using Python, you should definitely check outthe tutorial on the Internet at http://docs.python.org/2.7/tutorial/.Enter the name of any module, keyword, or topic to get help on writingPython programs and using Python modules.  To quit this help utility andreturn to the interpreter, just type "quit".To get a list of available modules, keywords, or topics, type "modules","keywords", or "topics".  Each module also comes with a one-line summaryof what it does; to list the modules whose summaries contain a given wordsuch as "spam", type "modules spam".help> qYou are now leaving help and returning to the Python interpreter.If you want to ask for help on a particular object directly from theinterpreter, you can type "help(object)".  Executing "help('string')"has the same effect as typing a particular string at the help> prompt.>>> help(help)Help on _Helper in module bpython.curtsiesfrontend._internal object:class _Helper(bpython._internal._Helper) |  Method resolution order: |      _Helper |      bpython._internal._Helper |      __builtin__.object |   |  Methods defined here: |   |  __call__(self, *args, **kwargs) |   |  __getattribute__(...) |      x.__getattribute__('name') <==> x.name |   |  __init__(self, repl=None) |   |  pager(self, output) |   |  ---------------------------------------------------------------------- |  Methods inherited from bpython._internal._Helper: |   |  __repr__(self) |   |  ---------------------------------------------------------------------- |  Data descriptors inherited from bpython._internal._Helper: |   |  __dict__ |      dictionary for instance variables (if defined) |   |  __weakref__ |      list of weak references to the object (if defined)~~~~~~~~~~~(END)


2.The Python Standard Library

2.1__builtin__

备注:__builtin__模块中的objects(类对象)、functions(函数方法)、data(常量)、exception(异常)可以直接使用,无需import。除了__builtin__中显示的其它所有类,都需要通过import导入才能使用。

>>> help('__builtin__')Help on built-in module __builtin__:NAME    __builtin__ - Built-in functions, exceptions, and other objects.FILE    (built-in)DESCRIPTION    Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.CLASSES    object        basestring            str            unicode        buffer        bytearray        classmethod        complex        dict        enumerate        file        float        frozenset        int            bool        list        long        memoryview        property        reversed        set        slice        staticmethod        super        tuple        type        xrange        class basestring(object)     |  Type basestring cannot be instantiated; it is the base for str and unicode.     |  .........FUNCTIONS    __import__(...)        __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module                Import a module. Because this function is meant for use by the Python        interpreter and not for general use it is better to use        importlib.import_module() to programmatically import a module.                The globals argument is only used to determine the context;        they are not modified.  The locals argument is unused.  The fromlist        should be a list of names to emulate ``from name import ...'', or an        empty list to emulate ``import name''.        When importing a module from a package, note that __import__('A.B', ...)        returns package A when fromlist is empty, but its submodule B when        fromlist is not empty.  Level is used to determine whether to perform         absolute or relative imports.  -1 is the original strategy of attempting        both absolute and relative imports, 0 is absolute, a positive number        is the number of parent directories to search relative to the current module.        abs(...)        abs(number) -> number                Return the absolute value of the argument.        all(...)        all(iterable) -> bool                Return True if bool(x) is True for all values x in the iterable.        If the iterable is empty, return True.    .........DATA    Ellipsis = Ellipsis    False = False    None = None    NotImplemented = NotImplemented    True = True    __debug__ = True    copyright = Copyright (c) 2001-2014 Python Software Foundati...ematisc...    credits =     Thanks to CWI, CNRI, BeOpen.com, Zope Corpor...opment.  ...    exit = Use exit() or Ctrl-D (i.e. EOF) to exit    help = Type help() for interactive help, or help(object) for help abou...    license = Type license() to see the full license text    quit = Use quit() or Ctrl-D (i.e. EOF) to exit(END)

2.1.1查看类class

备注:查看类对象的时候会显示类的描述,类中的方法定义。

例子1:查看int类,以及类的__add__方法。

>>> help('int')Help on class int in module __builtin__:class int(object) |  int(x=0) -> int or long |  int(x, base=10) -> int or long |   |  Convert a number or string to an integer, or return 0 if no arguments |  are given.  If x is floating point, the conversion truncates towards zero. |  If x is outside the integer range, the function returns a long instead. |   |  If x is not a number or if base is given, then x must be a string or |  Unicode object representing an integer literal in the given base.  The |  literal can be preceded by '+' or '-' and be surrounded by whitespace. |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to |  interpret the base from the string as an integer literal. |  >>> int('0b100', base=0) |  4 |   |  Methods defined here: |   |  __abs__(...) |      x.__abs__() <==> abs(x) |   |  __add__(...) |      x.__add__(y) <==> x+y......

>>> help('int.__add__')Help on wrapper_descriptor in int:int.__add__ = __add__(...)    x.__add__(y) <==> x+y

例子2:查看file类,以及类的close方法。

>>> help('file')Help on class file in module __builtin__:class file(object) |  file(name[, mode[, buffering]]) -> file object |   |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default), |  writing or appending.  The file will be created if it doesn't exist |  when opened for writing or appending; it will be truncated when |  opened for writing.  Add a 'b' to the mode for binary files.......

>>> help('file.close')Help on method_descriptor in file:file.close = close(...)    close() -> None or (perhaps) an integer.  Close the file.        Sets data attribute .closed to True.  A closed file cannot be used for    further I/O operations.  close() may be called more than once without    error.  Some kinds of file objects (for example, opened by popen())    may return an exit status upon closing.

2.1.2查看声明statement

备注:声明包括:print、if、while、else、import、from、try、except、with、as等等。

>>> help('print')The ``print`` statement***********************   print_stmt ::= "print" ([expression ("," expression)* [","]]                  | ">>" expression [("," expression)+ [","]])......

2.2非__builtin__

备注:在标准库中,但是不在__builtin__模块中。安装python之后即存在的模块。不需要安装其它第三方模块即可使用。比如os模块。

>>> dir()['__builtins__', '__doc__', '__name__', '__package__', 'help']>>> import os>>> dir()['__builtins__', '__doc__', '__name__', '__package__', 'help', 'os']>>> dir('os')Help on module os:NAME    os - OS routines for Mac, NT, or Posix depending on what system we're on.FILE    /usr/lib/python2.7/os.pyMODULE DOCS    http://docs.python.org/library/osDESCRIPTION    This exports:    ......


3.type命令

备注:type命令可以查看对象的类型,

>>> help('type')Help on class type in module __builtin__:class type(object) |  type(object) -> the object's type |  type(name, bases, dict) -> a new type |  ......>>> type(1)
>>> type('string')
>>> type([1])
>>> import os>>> type(os)
>>> type(os.chown)


4.dir命令

备注:dir命令如果不加任何参数即:dir(),则显示当前作用域的所有names。

         dir(模块):则显示此模块的所有子模块和函数方法。

>>> help('dir')Help on built-in function dir in module __builtin__:dir(...)    dir([object]) -> list of strings        If called without an argument, return the names in the current scope.    Else, return an alphabetized list of names comprising (some of) the attributes    of the given object, and of attributes reachable from it.    If the object supplies a method named __dir__, it will be used; otherwise    the default dir() logic is used and returns:      for a module object: the module's attributes.      for a class object:  its attributes, and recursively the attributes        of its bases.      for any other object: its attributes, its class's attributes, and        recursively the attributes of its class's base classes.(END)>>> dir(os)['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'P_NOWAIT', 'P_NOWAITO', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'ST_APPEND', 'ST_MANDLOCK', 'ST_NOATIME', 'ST_NODEV', 'ST_NODIRATIME', 'ST_NOEXEC', 'ST_NOSUID', 'ST_RDONLY', 'ST_RELATIME', 'ST_SYNCHRONOUS', 'ST_WRITE', 'TMP_MAX', 'UserDict', 'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'getenv', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getresgid', 'getresuid', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchown', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write']>>>

转载于:https://my.oschina.net/yulongblog/blog/663474

你可能感兴趣的文章
《PHP、MySQL和Apache入门经典(第5版)》一一2.7 基本安全规则
查看>>
《无线网络:理解和应对互联网环境下网络互连所带来的挑战》——2.5 3GPP2...
查看>>
《深入理解JavaScript》——2.6 JavaScript是广泛使用的吗
查看>>
Velocity官方指南-应用程序的属性
查看>>
《流量的秘密: Google Analytics网站分析与优化技巧(第3版)》一1.7 网站分析在企业中的位置...
查看>>
Xmemcached 1.2.2发布——支持遍历所有key
查看>>
Spark Streaming 1.6 流式状态管理分析
查看>>
ANTLR快餐教程(2) - ANTLR其实很简单
查看>>
dhtmlxCombo ztree
查看>>
第16期-Linux运维挑战赛
查看>>
Java的类型擦除
查看>>
好程序员web前端教程分享js闭包
查看>>
可以给redis的hash中的hashKey设置expire吗?
查看>>
Python获取本机 IP/MAC(多网卡)
查看>>
jQuery EasyUI 学习资料链接整理
查看>>
iOS textView 选中指向左上角
查看>>
OpenSSL学习(十二):基础-指令gendsa
查看>>
mac:python:pycharm:osx:可怕的case-sensitive硬盘格式
查看>>
MySQL备份与恢复
查看>>
Unsupported major.minor version
查看>>