什么是python的自省
作者:silencement 发布时间:2022-04-24 19:06:50
什么是自省?
在日常生活中,自省(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.
来源:https://www.py.cn/faq/python/12527.html


猜你喜欢
- python中字典是非常常用的数据类型,了解各种方法的作用及优缺点对于字典的使用非常有用。dict.clear() 的方法用于清空所有的键值
- 前言django,web开发中,用django-debug-toolbar来调试请求的接口,无疑是完美至极。 可能本人,见识博浅,才说完美至
- 导言:本文一步一步手把手教你打造一个极酷的三层分离的标准滑动门导航菜单,从思路、原理、步骤,手段可谓“无所不用其极”,即便你是菜鸟,相信你看
- 引言在Go语言中,我们通常会用到panic和recover来抛出错误和捕获错误,这一对操作在单协程环境下我们正常用就好了,并不会踩到什么坑。
- 本文实例讲述了Python实现读取机器硬件信息的方法。分享给大家供大家参考,具体如下:本人最近新学python ,用到关于机器的相关信息,经
- 1、基本原理访问网站扫码登录页,网站给浏览器返回一个二维码和一个唯一标志KEY浏览器开启定时轮询服务器,确认KEY对应的扫码结果用户使用ap
- Python socket C/S结构的聊天室应用服务端:#!/usr/bin/env python#coding:utf8 import
- 今天发现百度图片搜索结果的2级页面改版了,在浏览图片的时候很好用:如图:在浏览图片的时候,右侧的缩略图是这样交互的:因此,在整个浏览图片的过
- cmp()方法返回两个数的差的符号: -1 如果 x < y, 0 如果 x == y, 或者 1 如果 x > y
- 代码如下:import matplotlib.pyplot as pltx = [1,2,3,4,5,6,7,8]y = [5,2,4,2,
- 闭包account=0def atm(num,flag): global account  
- hello.html 文件代码如下:HelloWorld/templates/hello.html 文件代码:<h1>{{ he
- 1.安装python windows版本好:python-2.5.1.msi2.安装pycrypto windows版本号:py
- 今天主要向大家讲述的是优化SQL Server数据库的实际操作经验的总结,同时也有对其优化的实际操作中出现的一些问题的描述,以及对SQL S
- ASP中从数据库读取二进制文件数据代码:<%driver_name1="DRIVER={Microsoft&n
- forEach()函数从头到尾把数组遍历一遍。有三个参数分别是:数组元素,元素的索引,数组本身(如果是一个参数就是数组元素,也就是数组的值。
- 本文实例讲述了Python实现周期性抓取网页内容的方法。分享给大家供大家参考,具体如下:1.使用sched模块可以周期性地执行指定函数2.在
- 一、os模块os 模块是 Python中的一个内置模块,也是 Python中整理文件和目录最为常用的模块。该模块提供了非常丰富的方法用来处理
- 1. top命令和日志方式判定卡死的位置python代码忽然卡死,日志不输出,通过如下方式可以确定线程确实已经死掉了:# top 命令top
- 这篇文章主要介绍了python matplotlib饼状图参数及用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考