什么是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线程池的实现实例
Nov 18 Python
Python开发WebService系列教程之REST,web.py,eurasia,Django
Jun 30 Python
python中的函数用法入门教程
Sep 02 Python
python输入错误密码用户锁定实现方法
Nov 27 Python
解决Pycharm下面出现No R interpreter defined的问题
Oct 29 Python
python在TXT文件中按照某一字符串取出该字符串所在的行方法
Dec 10 Python
Python自动抢红包教程详解
Jun 11 Python
关于django 1.10 CSRF验证失败的解决方法
Aug 31 Python
python脚本之一键移动自定格式文件方法实例
Sep 02 Python
如何实现更换Jupyter Notebook内核Python版本
May 18 Python
Python中Selenium库使用教程详解
Jul 23 Python
用 Python 元类的特性实现 ORM 框架
May 19 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
桌面中心(四)数据显示
2006/10/09 PHP
[原创]效率较高的php下读取文本文件的代码
2008/07/02 PHP
php错误、异常处理机制(补充)
2012/05/07 PHP
XAMPP安装与使用方法详细解析
2013/11/27 PHP
Eclipse的PHP插件PHPEclipse安装和使用
2014/07/20 PHP
php强制下载文件函数
2016/08/24 PHP
windows环境下使用Composer安装ThinkPHP5
2018/05/18 PHP
从ThinkPHP3.2.3过渡到ThinkPHP5.0学习笔记图文详解
2019/04/03 PHP
如何实现浏览器上的右键菜单
2006/07/10 Javascript
JavaScript实现N皇后问题算法谜题解答
2014/12/29 Javascript
javascript转换日期字符串为Date日期对象的方法
2015/02/13 Javascript
JavaScript使用Math.Min返回两个数中较小数的方法
2015/04/06 Javascript
JS实现仿google、百度搜索框输入信息智能提示的实现方法
2015/04/20 Javascript
浅析webpack 如何优雅的使用tree-shaking(摇树优化)
2017/08/16 Javascript
微信小程序多列选择器range-key使用详解
2020/03/30 Javascript
详解react关于事件绑定this的四种方式
2018/03/09 Javascript
jQuery实现的鼠标拖动浮层功能示例【拖动div等任何标签】
2018/12/29 jQuery
vue父子模板传值问题解决方法案例分析
2020/02/26 Javascript
[01:01:36]Optic vs paiN 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
python自动化测试之setUp与tearDown实例
2014/09/28 Python
Python 批量刷博客园访问量脚本过程解析
2019/08/30 Python
python进行OpenCV实战之画图(直线、矩形、圆形)
2020/08/27 Python
Python爬取某平台短视频的方法
2021/02/08 Python
mui几种页面跳转方式对比总结概括
2017/08/18 HTML / CSS
世界上最大的专业美容用品零售商:Sally Beauty
2017/07/02 全球购物
美国鲍勃商店:Bob’s Stores
2018/07/22 全球购物
机械专业毕业生推荐信范文
2013/11/25 职场文书
2014高考励志标语
2014/06/05 职场文书
纪念九一八事变演讲稿:牢记历史,捍卫主权
2014/09/14 职场文书
专题组织生活会思想汇报
2014/10/01 职场文书
金砖之国观后感
2015/06/11 职场文书
干部考核工作总结
2015/08/12 职场文书
朋友圈早安励志语录!
2019/07/08 职场文书
创业计划书之餐饮馄饨店
2019/07/18 职场文书
《敬重卑微》读后感3篇
2019/11/26 职场文书
python 使用Tensorflow训练BP神经网络实现鸢尾花分类
2021/05/12 Python