什么是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生成随机密码
Mar 10 Python
Python实现将一个大文件按段落分隔为多个小文件的简单操作方法
Apr 17 Python
pandas获取groupby分组里最大值所在的行方法
Apr 20 Python
Linux下Pycharm、Anaconda环境配置及使用踩坑
Dec 19 Python
python使用threading.Condition交替打印两个字符
May 07 Python
numpy.linspace函数具体使用详解
May 27 Python
Python 实用技巧之利用Shell通配符做字符串匹配
Aug 23 Python
python 实现将Numpy数组保存为图像
Jan 09 Python
Python搭建Keras CNN模型破解网站验证码的实现
Apr 07 Python
Python实现自动打开电脑应用的示例代码
Apr 17 Python
通过代码实例解析Pytest运行流程
Aug 20 Python
基于Python的接口自动化unittest测试框架和ddt数据驱动详解
Jan 27 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
JQuery 无废话系列教程(一) jquery入门 [推荐]
2009/06/23 Javascript
基于jQuery替换table中的内容并显示进度条的代码
2011/08/02 Javascript
JavaScript函数的4种调用方法详解
2014/04/22 Javascript
jQuery修改li下的样式以及li下的img的src的值的方法
2014/11/02 Javascript
Javascript中使用A标签获取当前目录的绝对路径方法
2015/03/02 Javascript
js设置document.domain实现跨域的注意点分析
2015/05/21 Javascript
详解js的六大数据类型
2016/12/27 Javascript
JS中实现函数return多个返回值的实例
2017/02/21 Javascript
利用Jasmine对Angular进行单元测试的方法详解
2017/06/12 Javascript
详解如何在Vue项目中导出Excel
2019/04/19 Javascript
基于JS实现一个随机生成验证码功能
2019/05/29 Javascript
详解Vue项目引入CreateJS的方法(亲测可用)
2019/05/30 Javascript
layui固定下拉框的显示条数(有滚动条)的方法
2019/09/10 Javascript
vue随机验证码组件的封装实现
2020/02/19 Javascript
echarts实现晶体球面投影的实例教程
2020/10/10 Javascript
JavaScript中条件语句的优化技巧总结
2020/12/04 Javascript
[10:05]DOTA2-DPC中国联赛 正赛 iG vs PSG.LGD 选手采访
2021/03/11 DOTA
Python中使用asyncio 封装文件读写
2016/09/11 Python
keras中epoch,batch,loss,val_loss用法说明
2020/07/02 Python
CSS3实现的炫酷菜单代码分享
2015/03/12 HTML / CSS
CSS3 函数技巧 用css 实现js实现的事情(clac Counters Tooltip)
2017/08/15 HTML / CSS
Html5页面中的返回实现的方法
2018/02/26 HTML / CSS
西班牙用户之间买卖视频游戏的平台:Wakkap
2020/03/21 全球购物
国际花店:Pickup Flowers
2020/04/10 全球购物
Linux管理员面试题 Linux admin interview questions
2016/07/08 面试题
平面设计自荐信
2013/10/07 职场文书
大学生职业规划论文
2014/01/11 职场文书
古汉语文学求职信范文
2014/03/16 职场文书
作风大整顿心得体会
2014/09/10 职场文书
四风问题个人对照检查剖析材料
2014/09/27 职场文书
党的群众路线查摆剖析材料
2014/10/10 职场文书
2015年元旦晚会活动总结(学生会)
2014/11/28 职场文书
优秀教育工作者事迹材料
2014/12/24 职场文书
mysql备份策略的实现(全量备份+增量备份)
2021/07/07 MySQL
Win11如何修改dns?Win11修改dns图文教程
2022/01/18 数码科技
oracle重置序列从0开始递增1
2022/02/28 Oracle