什么是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模块MySQLdb安装详解
Apr 09 Python
Django REST为文件属性输出完整URL的方法
Dec 18 Python
python3实现公众号每日定时发送日报和图片
Feb 24 Python
python爬虫正则表达式之处理换行符
Jun 08 Python
Python从Excel中读取日期一列的方法
Nov 28 Python
Python数据库小程序源代码
Sep 15 Python
在Python中字符串、列表、元组、字典之间的相互转换
Nov 15 Python
python 实现在shell窗口中编写print不向屏幕输出
Feb 19 Python
python中使用input()函数获取用户输入值方式
May 03 Python
基于python 取余问题(%)详解
Jun 03 Python
Python实现迪杰斯特拉算法并生成最短路径的示例代码
Dec 01 Python
教你漂亮打印Pandas DataFrames和Series
May 29 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
基于mysql的bbs设计(三)
2006/10/09 PHP
PHP5中的时间相差8小时的解决办法
2008/03/28 PHP
php实现的通用图片处理类
2015/03/24 PHP
php中array_column函数简单实现方法
2016/07/11 PHP
微信支付PHP SDK ―― 公众号支付代码详解
2016/09/13 PHP
php的命名空间与自动加载实现方法
2019/08/25 PHP
键盘KeyCode值列表汇总
2013/11/26 Javascript
innerText 使用示例
2014/01/23 Javascript
js进行表单验证实例分析
2015/02/10 Javascript
jquery实现动态操作select选中
2015/02/11 Javascript
javascript中 try catch用法
2015/08/16 Javascript
浅谈JavaScript中的apply/call/bind和this的使用
2017/02/26 Javascript
原生JS写Ajax的请求函数功能
2017/12/22 Javascript
Angular2中监听数据更新的方法
2018/08/31 Javascript
javascript匿名函数中的'return function()'作用
2018/10/15 Javascript
Vue动态面包屑功能的实现方法
2019/07/01 Javascript
vue 解决form表单提交但不跳转页面的问题
2019/10/30 Javascript
浅谈vue 锚点指令v-anchor的使用
2019/11/13 Javascript
Vue 实现拨打电话操作
2020/11/16 Javascript
从Python程序中访问Java类的简单示例
2015/04/20 Python
python实现批量下载新浪博客的方法
2015/06/15 Python
python利用不到一百行代码实现一个小siri
2017/03/02 Python
Python中easy_install 和 pip 的安装及使用
2017/06/05 Python
python抓取文件夹的所有文件
2018/02/27 Python
python读取一个目录下所有txt里面的内容方法
2018/06/23 Python
python3+selenium实现qq邮箱登陆并发送邮件功能
2019/01/23 Python
Python3实现汉语转换为汉语拼音
2019/07/08 Python
ML神器:sklearn的快速使用及入门
2019/07/11 Python
python中Django文件上传方法详解
2020/08/05 Python
美国专业级皮肤病和spa品质护肤品的高级零售网站:SkinCareRx
2017/02/06 全球购物
巴黎一票通:The Paris Pass
2018/02/10 全球购物
职业教育毕业生求职信
2013/11/09 职场文书
幼儿园教师个人反思
2014/01/30 职场文书
老公保证书范文
2014/04/29 职场文书
地球一小时宣传标语
2014/06/24 职场文书
预备党员入党感言
2015/08/01 职场文书