什么是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操作Mysql实例代码教程在线版(查询手册)
Feb 18 Python
在Django框架中编写Context处理器的方法
Jul 20 Python
Python实现二叉树结构与进行二叉树遍历的方法详解
May 24 Python
Python设计模式之装饰模式实例详解
Jan 21 Python
python实现远程控制电脑
May 23 Python
python实现简单五子棋游戏
Jun 18 Python
django实现类似触发器的功能
Nov 15 Python
Python正则表达式急速入门(小结)
Dec 16 Python
使用npy转image图像并保存的实例
Jul 01 Python
Python3如何实现Win10桌面自动切换
Aug 11 Python
python3中编码获取网页的实例方法
Nov 16 Python
python pandas 解析(读取、写入)CSV 文件的操作方法
Dec 24 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
IIS6+PHP5+MySQL5+Zend Optimizer+phpMyAdmin安装配置图文教程 2009年
2009/06/08 PHP
如何在Ubuntu下启动Apache的Rewrite功能
2013/07/05 PHP
PHP中应该避免使用同名变量(拆分临时变量)
2015/04/03 PHP
判断、添加和删除WordPress置顶文章的相关PHP函数小结
2015/12/10 PHP
php 实现银联商务H5支付的示例代码
2019/10/12 PHP
Javascript 个人笔记(没有整理,很乱)
2007/07/07 Javascript
从JavaScript 到 JQuery (1)学习小结
2009/02/12 Javascript
js修改table中Td的值(定义td的单击事件)
2013/01/10 Javascript
jQuery插件开发的两种方法及$.fn.extend的详解
2014/01/16 Javascript
js实现的点击数量加一可操作数据库
2014/05/09 Javascript
深入理解javascript作用域和闭包
2014/09/23 Javascript
node.js中的events.EventEmitter.listenerCount方法使用说明
2014/12/08 Javascript
jQuery中prevAll()方法用法实例
2015/01/08 Javascript
jQuery中next方法用法实例
2015/04/24 Javascript
简介JavaScript中valueOf()方法的使用
2015/06/05 Javascript
vue 2.0组件与v-model详解
2017/03/27 Javascript
select自定义小三角样式代码(实用总结)
2017/08/18 Javascript
使用async、enterproxy控制并发数量的方法详解
2018/01/02 Javascript
js遍历添加栏目类添加css 再点击其它删除css【推荐】
2018/06/12 Javascript
js微信分享接口调用详解
2019/07/23 Javascript
在Python中操作字典之update()方法的使用
2015/05/22 Python
python中找出numpy array数组的最值及其索引方法
2018/04/17 Python
Win8下python3.5.1安装教程
2020/07/29 Python
学生信息管理系统python版
2018/10/17 Python
django框架自定义模板标签(template tag)操作示例
2019/06/24 Python
如何使用python操作vmware
2019/07/27 Python
python+requests接口压力测试500次,查看响应时间的实例
2020/04/30 Python
HTML5 自动聚焦(autofocus)属性使用介绍
2013/08/07 HTML / CSS
中国首家奢侈品O2O网购平台:第五大道奢侈品网
2017/12/14 全球购物
日本索尼音乐商店:Sony Music Shop
2018/07/17 全球购物
Stio官网:男女、儿童户外服装
2019/12/13 全球购物
文明礼仪标语
2014/06/13 职场文书
2014财务部年度工作总结
2014/12/08 职场文书
2015试用期转正工作总结
2014/12/12 职场文书
2015年教师节活动总结
2015/03/20 职场文书
详解CocosCreator项目结构机制
2021/04/14 Javascript