什么是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命令行参数解析OptionParser类用法实例
Oct 09 Python
Python中的zip函数使用示例
Jan 29 Python
深入剖析Python的爬虫框架Scrapy的结构与运作流程
Jan 20 Python
python进阶_浅谈面向对象进阶
Aug 17 Python
对Tensorflow中权值和feature map的可视化详解
Jun 14 Python
python随机数分布random测试
Aug 27 Python
Python单元和文档测试实例详解
Apr 11 Python
Python 实现文件读写、坐标寻址、查找替换功能
Sep 11 Python
python 二维矩阵转三维矩阵示例
Nov 30 Python
pycharm如何实现跨目录调用文件
Feb 28 Python
Django实现whoosh搜索引擎使用jieba分词
Apr 08 Python
Python趣味入门教程之循环语句while
Aug 26 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
PHP中$this和$that指针使用实例
2015/01/06 PHP
浅析ThinkPHP缓存之快速缓存(F方法)和动态缓存(S方法)(日常整理)
2015/10/26 PHP
PHP 微信支付类 demo
2015/11/30 PHP
PHP与以太坊交互详解
2018/08/24 PHP
PHP getDocNamespaces()函数讲解
2019/02/03 PHP
100个不能错过的实用JS自定义函数
2014/03/05 Javascript
javascript实现的图片切割多块效果实例
2015/05/07 Javascript
Webpack 实现 AngularJS 的延迟加载
2016/03/02 Javascript
vuejs响应用户事件(如点击事件)
2017/03/14 Javascript
jquery插件canvaspercent.js实现百分比圆饼效果
2017/07/18 jQuery
Vue自定义过滤器格式化数字三位加一逗号实现代码
2018/03/23 Javascript
JavaScript 对引擎、运行时、调用堆栈的概述理解
2018/10/22 Javascript
Vue中Table组件Select的勾选和取消勾选事件详解
2019/03/19 Javascript
页面内锚点定位及跳转方法总结(推荐)
2019/04/24 Javascript
简单了解vue.js数组的常用操作
2019/06/17 Javascript
JavaScript实现单图片上传并预览功能
2019/09/30 Javascript
使用axios请求时,发送formData请求的示例
2019/10/29 Javascript
微信小程序实现上传多个文件 超过10个
2020/03/30 Javascript
Array.filter中如何正确使用Async
2020/11/04 Javascript
python文件和目录操作方法大全(含实例)
2014/03/12 Python
详解Python爬虫的基本写法
2016/01/08 Python
Python实现的寻找前5个默尼森数算法示例
2018/03/25 Python
python3实现SMTP发送邮件详细教程
2018/06/19 Python
Python实现数据可视化看如何监控你的爬虫状态【推荐】
2018/08/10 Python
python实现简单图书管理系统
2019/11/22 Python
关于python中remove的一些坑小结
2021/01/04 Python
印度网上购物首选目的地:Flipkart
2016/08/01 全球购物
Lacoste澳大利亚官网:服装、鞋类及配饰
2018/11/14 全球购物
澳大利亚在线高跟鞋商店:Shoe Me
2019/11/19 全球购物
食品行业求职人的自我评价
2014/01/19 职场文书
高等教育学自荐书范文
2014/02/10 职场文书
2014最新自愿离婚协议书范本
2014/11/19 职场文书
整改通知书格式
2015/04/22 职场文书
家庭聚会祝酒词
2015/08/11 职场文书
Python代码风格与编程习惯重要吗?
2021/06/03 Python
Python  序列化反序列化和异常处理的问题小结
2022/12/24 Python