第12章-自省¶
无论您是刚接触过python、使用了几年还是您是一名专家,了解如何使用python的自省功能都可以帮助您理解您的代码以及刚刚下载的带有蹩脚文档的新包。自省是一个花哨的词,意思是观察自己,思考自己的想法、感觉和欲望。在Python世界中,内省实际上是类似的。在本例中,内省是使用python来计算python。在本章中,您可以学习如何使用python为您自己提供有关正在处理或试图学习的代码的线索。有些人甚至称之为调试的一种形式。
下面是我们要介绍的内容:
类型
迪尔
帮助
python类型¶
您可能不知道这一点,但python可能只是您的类型。是的,python可以告诉您拥有什么类型的变量,或者从函数返回什么类型的变量。这是一个非常方便的小工具。让我们看几个例子来说明这一切:
>>> x = "test"
>>> y = 7
>>> z = None
>>> type(x)
<class 'str'>
>>> type(y)
<class 'int'>
>>> type(z)
<class 'NoneType'>
如您所见,python有一个名为 type 这可以告诉你什么是什么。在我的现实生活中,我用 type 帮助我了解当我的数据库数据损坏或不符合我的期望时会发生什么。我只需添加几行并打印出每行的数据及其类型。当我被我写的一些愚蠢的代码弄得目瞪口呆时,这帮了我很大的忙。
python目录¶
什么是dir?当别人说或做蠢事时,你会说些什么吗?不是在这种情况下!不,在python星球上,dir关键字用于告诉程序员传入对象中有哪些属性和方法。如果忘记传入对象,dir将返回当前作用域中的名称列表。像往常一样,通过几个例子,这更容易理解。
>>> dir("test")
['__add__', '__class__', '__contains__', '__delattr__',
'__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__getslice__', '__gt__',
'__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__str__', 'capitalize', 'center',
'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
因为python中的所有内容都是一个对象,所以我们可以将一个字符串传递给dir,并找出它有哪些方法。挺干净的,嗯?现在让我们用一个导入的模块来尝试一下:
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__',
'__name__', '__plen', '__stderr__', '__stdin__', '__stdout__',
'_getframe', 'api_version', 'argv', 'builtin_module_names',
'byteorder', 'call_tracing', 'callstats', 'copyright',
'displayhook', 'dllhandle', 'exc_clear', 'exc_info',
'exc_traceback', 'exc_type', 'exc_value', 'excepthook',
'exec_prefix', 'executable', 'exit', 'exitfunc',
'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding',
'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'hexversion',
'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
'path_importer_cache', 'platform', 'prefix', 'setcheckinterval',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin',
'stdout', 'version', 'version_info', 'warnoptions', 'winver']
现在,这很方便!如果你还没弄清楚,那么 dir 对于那些您已经下载(或即将下载)但几乎没有文档的第三方软件包,该功能非常方便。在这些情况下,您如何了解可用的方法?好, dir 会帮你解决的。当然,有时文档在代码本身中,这会使我们了解内置帮助实用程序。
Python 帮助!¶
python附带了一个方便的帮助实用程序。只需在python shell中键入“help()”(减去引号),您将看到以下指示(python版本可能有所不同)
>>> help()
Welcome to Python 2.6! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return 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 summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
help>
请注意,您现在有一个“帮助>”提示,而不是“>>>”。当您处于帮助模式时,您可以浏览Python中的各种模块、关键字和主题。另外请注意,当输入“modules”这个词时,当python搜索其library文件夹以获取一个列表时,您将看到一个延迟。如果您安装了许多第三方模块,这可能需要相当长的时间,所以请准备在您等待时为自己修复一个Mocha。一旦完成了,就按照指示去玩,我想你会明白要点的。
总结¶
现在,您知道了如何使用一个未知的模块,并通过使用Python的一些内置功能来了解它。您将发现自己一次又一次地使用这些命令来帮助您学习Python。正如我前面提到的,您会发现这些工具对于不相信文档的第三方模块特别有用。