天天看点

Python 帮助使用

对于初学者而言,开始不太了解对象或者库都有神马东西,所以如何去获取这些属性和方法非常重要。

一、一般以双下划线开头并结尾的变量名是用来表示Python实现细节的命名模式。而没有下划线的属性是字符串对象能够调用的方法。dir简单的给出了方法的名称,而help可以查看具体是干什么的。如下:

>>> dir(str)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

>>> 

>>> help(str.upper)

Help on method_descriptor:

upper(...)

    S.upper() -> str

    Return a copy of S converted to uppercase.

二、内置的dir函数是抓取对象内可用所有属性列表的简单方式,它可以调用任何有属性的对象。例如可以找出标准库sys模块中有什么可以用,可以将其导入,并传递给dir

>>> import sys

>>> dir(sys)

['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']

三、要想知道对象类型提供了哪些属性,可以运行dir并传入所需类型的常量,如查看列表和字符串的属性。dir([]) dir('')

四、PyDoc是Python程序代码,内置的函数help会调用PyDoc从而产生简单的文字报表如:help(str.upper)

本文转自 aklaus 51CTO博客,原文链接:http://blog.51cto.com/aklaus/1768824