什么是python的自省


Posted in Python onJune 21, 2020

什么是自省?

在日常生活中,自省(introspection)是一种自我检查行为。

在计算机编程中,自省是指这种能力:检查某些事物以确定它是什么、它知道什么以及它能做什么。自省向程序员提供了极大的灵活性和控制力。

说的更简单直白一点:自省就是面向对象的语言所写的程序在运行时,能够知道对象的类型。简单一句就是,运行时能够获知对象的类型。

例如python, buby, object-C, c++都有自省的能力,这里面的c++的自省的能力最弱,只能够知道是什么类型,而像python可以知道是什么类型,还有什么属性。

最好的理解自省就是通过例子: Type introspection 这里是各种编程语言中自省(introspection)的例子(这个链接里的例子很重要,也许你很难通过叙述理解什么是introspection,但是通过这些例子,一下子你就可以理解了)

回到Python,Python中比较常见的自省(introspection)机制(函数用法)有: dir(),type(), hasattr(), isinstance(),通过这些函数,我们能够在程序运行时得知对象的类型,判断对象是否存在某个属性,访问对象的属性。

dir()

dir() 函数可能是 Python 自省机制中最著名的部分了。它返回传递给它的任何对象的属性名称经过排序的列表。如果不指定对象,则 dir() 返回当前作用域中的名称。让我们将 dir() 函数应用于 keyword 模块,并观察它揭示了什么:

>>> import keyword
>>> dir(keyword)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'iskeyword', 'kwlist', 'main']

type()

type() 函数有助于我们确定对象是字符串还是整数,或是其它类型的对象。它通过返回类型对象来做到这一点,可以将这个类型对象与 types 模块中定义的类型相比较:

>>> type(42)<class 'int'>
>>> type([])<class 'list'>

isinstance()

可以使用 isinstance() 函数测试对象,以确定它是否是某个特定类型或定制类的实例:

>>> isinstance("python", str)
True

python自省中help用法扩展:

打开python的IDLE,就进入到了python解释器中,python解释器本身是被认为是一个主模块,然后在解释器提示符>>>下输入一些我们想了解的信息,所以首先我们会先寻求帮助,所以输入help,接着输入help(),我们就进入了help utility,然后循着提示keywords,modules,以了解python的关键字以及python自带的或者我们额外安装和定义的模块,如果要退出,输入'q',然后回车。

如果我们想了解某个对象(python里面所有对象都可以认为是对象),也可以求助也help(),不过要在括号里输入对象的名称,格式help(object),例如help(print),鉴于对象的自省内容太多,有的只粘贴出部分内容。

>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()

Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.6/tutorial/.

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".
...
help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

False        def         if         raise
None        del         import       return
True        elif        in         try
and         else        is         while
as         except       lambda       with
assert       finally       nonlocal      yield
break        for         not         
class        from        or         
continue      global       pass        

help> modules

Please wait a moment while I gather a list of all available modules...

PIL         base64       idlelib       runpy
__future__     bdb         idna        runscript
__main__      binascii      idna_ssl      sched
_ast        binhex       imaplib       scrolledlist
_asyncio      bisect       imghdr       search
_bisect       browser       imp         
...
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".
>>> help('print')
Help on built-in function print in module builtins:

print(...)
  print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  
  Prints the values to a stream, or to sys.stdout by default.
  Optional keyword arguments:
  file: a file-like object (stream); defaults to the current sys.stdout.
  sep:  string inserted between values, default a space.
  end:  string appended after the last value, default a newline.
  flush: whether to forcibly flush the stream.

到此这篇关于什么是python的自省的文章就介绍到这了,更多相关python自省是什么内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python写的创建文件夹自定义函数mkdir()
Aug 25 Python
python 简单的多线程链接实现代码
Aug 28 Python
Python探索之自定义实现线程池
Oct 27 Python
使用Pyinstaller的最新踩坑实战记录
Nov 08 Python
python编写分类决策树的代码
Dec 21 Python
pyqt5简介及安装方法介绍
Jan 31 Python
Python中安装easy_install的方法
Nov 18 Python
Django使用中间件解决前后端同源策略问题
Sep 02 Python
Python namedtuple命名元组实现过程解析
Jan 08 Python
python datetime时间格式的相互转换问题
Jun 11 Python
通过实例简单了解Python sys.argv[]使用方法
Aug 04 Python
Python NumPy灰度图像的压缩原理讲解
Aug 04 Python
python的json包位置及用法总结
Jun 21 #Python
为什么相对PHP黑python的更少
Jun 21 #Python
通过自学python能找到工作吗
Jun 21 #Python
python中常见错误及解决方法
Jun 21 #Python
python安装后的目录在哪里
Jun 21 #Python
浅谈Python 函数式编程
Jun 20 #Python
音频处理 windows10下python三方库librosa安装教程
Jun 20 #Python
You might like
一个改进的UBB类
2006/10/09 PHP
PHP中的cookie不用刷新就生效的方法
2012/02/04 PHP
php在window iis的莫名问题的测试方法
2013/05/14 PHP
PHP安全的URL字符串base64编码和解码
2014/06/19 PHP
PHP实现一维数组转二维数组的方法
2015/02/25 PHP
PHP版微信第三方实现一键登录及获取用户信息的方法
2016/10/14 PHP
PHP获取页面执行时间的方法(推荐)
2016/12/10 PHP
laravel Model 执行事务的实现
2019/10/10 PHP
PHP高并发和大流量解决方案整理
2019/12/24 PHP
jquery中使用ajax获取远程页面信息
2011/11/13 Javascript
JavaScript中prototype为对象添加属性的误区介绍
2013/10/15 Javascript
jquery根据name属性查找的小例子
2013/11/21 Javascript
我的Node.js学习之路(一)
2014/07/06 Javascript
JQuery中ajax方法访问web服务实例
2015/07/18 Javascript
基于jQuery实现音乐播放试听列表
2016/04/14 Javascript
微信小程序 数据访问实例详解
2016/10/08 Javascript
js 概率计算(简单版)
2017/09/12 Javascript
浅析vue中常见循环遍历指令的使用 v-for
2018/04/18 Javascript
JS获取并处理php数组的方法实例分析
2018/09/04 Javascript
js贪心算法 钱币找零问题代码实例
2019/09/11 Javascript
Vue实现圆环进度条的示例
2021/02/06 Vue.js
[32:07]完美世界DOTA2联赛PWL S3 LBZS vs Rebirth 第一场 12.16
2020/12/17 DOTA
利用python实现xml与数据库读取转换的方法
2017/06/17 Python
对python pandas读取剪贴板内容的方法详解
2019/01/24 Python
pymongo中聚合查询的使用方法
2019/03/22 Python
Python中的list与tuple集合区别解析
2019/10/12 Python
调用其他python脚本文件里面的类和方法过程解析
2019/11/15 Python
解决Windows下python和pip命令无法使用的问题
2020/08/31 Python
分享一个H5原生form表单的checkbox特效代码
2018/02/26 HTML / CSS
快速实现一个简单的canvas迷宫游戏的示例
2018/07/04 HTML / CSS
美国畅销的跑步机品牌:ProForm
2017/02/06 全球购物
环境科学专业个人求职信
2013/12/15 职场文书
优秀小学生家长评语
2014/01/30 职场文书
校园文化建设方案
2014/02/03 职场文书
《猴子种树》教学反思
2014/02/14 职场文书
员工考核评语大全
2014/04/26 职场文书