Python組み込みメソッド、タイプの概要

ここに画像の説明を挿入します
公式文書の第2章から要約されています。ソースコードを参照してください。

概要概要

dir(__builtins__)

ここに画像の説明を挿入します
これはTyporaのMaizeテーマの表示です。分類は比較的細かく、CSDNと比較すると、execとprintが表示されます。
赤いものは、エラーや警告などの__name__などの変更されたシステム値であり、さまざまな環境に応じて関連情報を報告します。
__import__から始まる黄色のフォントの数は68です!

dir(__builtins__)
ArithmeticError AssertionError AttributeError BaseException BlockingIOError BrokenPipeError BufferError
BytesWarning ChildProcessError ConnectionAbortedError ConnectionError ConnectionRefusedError 
ConnectionResetError DeprecationWarning EOFError Ellipsis EnvironmentError Exception False 
FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError 
ImportWarning IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt
LookupError MemoryError ModuleNotFoundError NameError None NotADirectoryError NotImplemented 
NotImplementedError OSError OverflowError PendingDeprecationWarning PermissionError ProcessLookupError
RecursionError ReferenceError ResourceWarning RuntimeError RuntimeWarning StopAsyncIteration 
StopIteration 
SyntaxError SyntaxWarning SystemError SystemExit TabError TimeoutError True TypeError UnboundLocalError
UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning 
ValueError Warning WindowsError ZeroDivisionError __build_class__ __debug__ __doc__ __import__ __loader__
__name__ __package__ __spec__ abs all any ascii bin bool breakpoint bytearray bytes callable chr 
classmethod compile complex copyright credits delattr dict dir divmod enumerate eval exec exit filter 
float format frozenset getattr globals hasattr hash help hex id input int isinstance issubclass iter len 
license list locals map max memoryview min next object oct open ord pow print property quit range repr 
reversed round set setattr slice sorted staticmethod str sum super tuple type vars zip
for i in dir(__builtins__):
	print(i,str(eval('type(%s)'%i))[8:-2])

分類

エラー

ArithmeticError type
AssertionError type
AttributeError type
BlockingIOError type
BrokenPipeError type
BufferError type
ChildProcessError type
ConnectionAbortedError type
ConnectionError type
ConnectionRefusedError type
ConnectionResetError type
EOFError type
EnvironmentError type
FileExistsError type
FileNotFoundError type
FloatingPointError type
IOError type
ImportError type
IndentationError type
IndexError type
InterruptedError type
IsADirectoryError type
KeyError type
LookupError type
MemoryError type
ModuleNotFoundError type
NameError type
NotADirectoryError type
NotImplementedError type
OSError type
OverflowError type
PermissionError type
ProcessLookupError type
RecursionError type
ReferenceError type
RuntimeError type
SyntaxError type
SystemError type
TabError type
TimeoutError type
TypeError type
UnboundLocalError type
UnicodeDecodeError type
UnicodeEncodeError type
UnicodeError type
UnicodeTranslateError type
ValueError type
WindowsError type
ZeroDivisionError type

警告

BytesWarning type
DeprecationWarning type
FutureWarning type
ImportWarning type
PendingDeprecationWarning type
ResourceWarning type
RuntimeWarning type
SyntaxWarning type
UnicodeWarning type
UserWarning type
Warning type

例外

BaseException type 所有异常的公共基类
Exception typetrypass except Exception as e:e,用来回馈错误信息
GeneratorExit type 请求一个生成器退出
KeyboardInterrupt type 键盘中断模块
StopAsyncIteration type 停止异步迭代?
StopIteration type 停止迭代?
SystemExit type 请求退出解释器

公式文書第3章:組み込み定数

絶え間ない

Pythonスタディノート(2)変数、定数、およびデータ型
python-組み込み定数

Ellipsis ellipsis 省略号,等价...,在语法中有特殊含义:[1,2,3,[...]];可以被赋值
False bool 布尔值的假,无法赋值
None NoneType 一般做特殊数值,例如i=Noneif i;若函数无返回,会默认返回None,无法赋值
NotImplemented NotImplementedType 未实现,双目运算特殊方法:当执行a1 == a2时(即调用__eq__(a1,a2)),返回NotImplemented时,Python会自动交换参数再次调用__eq__(a2,a1);可以被赋值
True bool 布尔值的真,无法赋值
__debug__ bool:python -O时,为真,否则为假。-O时会移除所有的assert语句

サイトモジュールによって追加された定数

python sys.exit()、break、exit()、quit()、os._exit()、returnの違い

quit _sitebuiltins.Quitter
exit _sitebuiltins.Quitter
copyright _sitebuiltins._Printer 显示解释器版权信息
credits _sitebuiltins._Printer 显示解释器作者信息
license _sitebuiltins._Printer 许可信息 很长

シェルで使用されていますが、2つのコードを記述しました。どちらも、コードの実行中に終了できます。

その他の定数

__doc__ NoneType 显示当前模块的文档
__name__ str 显示当前模块的名称,常见于if __name__=='__main__':
__package__ NoneType
__spec__ NoneType
__loader__ _frozen_importlib_external.SourceFileLoader
help _sitebuiltins._Helper 注意,该方法直接输出,不会返回,没必要使用print(help(help))

Pythonはヘルプをファイルに書き込みます

方法

ここに画像の説明を挿入します
公式文書第2章:組み込み関数

環境、クラス

__import__ builtin_function_or_method 显示模块的所在位置
callable 对象是否可被调用
delattr 删除对象中的属性,面向对象中会应用到
dir 返回对象的属性
getattr 得到对象中的属性
globals 返回全局变量已字典形式。g=globals().copy() for i,j in g.items(): print(i,j)
hasattr 检查对象是否拥有某个属性;判断类实例中是否含有某个属性
id 返回对象的内存地址
isinstance 判断类型
issubclass 判断某个类是否是一个类的子类
locals 返回全局变量已字典形式
setattr 设置对象的属性
vars 不带参数,相当于locals()。带参数,相当于object.__dict__。

その他

__build_class__ builtin_function_or_method 类语句使用的内部助手函数
breakpoint builtin_function_or_method 断点,默认情况下,这将使您进入pdb调试器。

数値

abs 绝对值
bin 十进制转二进制
divmod 返回除数和被除数的商数和余数
hash 计算对象的哈希值
hex 十进制转十六进制
oct 十进制转八进制
pow 返回a的b次幂
round 四舍五入

反復可能なオブジェクト

all  多项集/可迭代对象,包含bool值为False的,返回False,反之True,即便多项集为空
any 多项集,包含bool值为True的,返回True,反之False。空字符串是空序列,字符串'0'boolTrue
iter 生成迭代器
len 返回可迭代对象的数量,返回容器中的项数
max 返回容器中的最大值
min 返回容器中的最小值
next 返回迭代器当前输出
sorted 返回容器的排序已列表形式
sum 返回容器中所有数值的和

リスト、文字列、タプルは順序付けられたシーケンスなので、セットと辞書は何と呼ばれますか?

一般的に言って、それらはすべて反復可能なオブジェクトです。公式の中国語のドキュメントでは、マルチセットという用語を取得し、有道辞書では、コンテナという用語を取得しました。

Iterableは、シーケンス、反復をサポートするコンテナー、またはその他の反復可能なオブジェクトにすることができます。

セットオブジェクトは、一意のハッシュ可能なオブジェクトで構成される順序付けられていない多項式セットです。

ストリング

ascii 有点像'unicode_escape',不过ascii返回的是字符串不是字节串,ascii('\nabc香')
chr 数值转对应序的字符
eval 执行字符串的表达式,返回结果
exec 执行字符串的语句
format 格式化字符串
compile 返回evalexec表达式的编译的可执行字节串
input 显示字符串并获取输入字符
open 生成文件对象
ord 返回字符对应的字序
print 打印字符串
repr 返回对象的规范字符串表示形式

タイプ

コアタイプ

bool 布尔
bytes 字节字符串,不可变序列
complex 复数
dict 字典
float 浮点
int 整数
list 列表
set 集合
str 字符串
tuple 元组

ここでは、追加のマーキングのない文字通りの数量がコアタイプとして分類されます

他のタイプ

None NoneType 
NotImplemented NotImplementedType 

拡張タイプ

bytearray 字节字符串,可变序列
frozenset 冻结集合
memoryview 字符字节串,内存视图,切片操作不会生成临时数据
range 一个不可变的序列类型,多元写法类似于切片
slice 切片

イテレータ

enumerate 迭代器,相当于相当于iter,但返回的是(索引,元素)的组合
filter 迭代器,附加判断布尔的方法,为真则返回。filter(function or None, iterable)
map 迭代器,附加运算方法,返回运算结果map(function, iterable, ...)
reversed 迭代器,将被迭代对象逆序输出
zip 迭代器,返回容器A与容器B序列对应的元组

クラス関連

classmethod 将函数转换为类方法;把一个方法封装成类方法
object 返回一个没有特征的新对象;object 是所有类的基类
property 返回 property 属性
staticmethod 将方法转换为静态方法
super 返回一个代理对象;它会将方法调用委托给 type 的父类或兄弟类

キーワード

import keyword
keyword.kwlist

False None True __peg_parser__ and as assert async await break class continue def del 
elif else except finally for from global if import in is lambda nonlocal not or pass 
raise return try while with yield

数値

False 布尔假
None NoneType
True 布尔真

判定

and 都为真则真,反之为假
in 元素是否在容器中
is 判断两个变量是否是同一变量:id()是否一样
notnot innot A is B
or 都为假则假,任意真为真

クラス関数

class 定义类
def 定义函数
global 声明全局变量
nonlocal 声明非局部变量
return 函数返回
yield 生成器
lambda 匿名函数

async 异步
await 等候

処理する

as 相当于赋值=
from 从模块中
import 导入

if 根据判断结果执行对应语句
elif 二段判断
else 判断剩余

try 判断语句是否成功
except 如果异常
finally 无论是否异常

for 迭代循环
while 条件循环
break 跳出循环
continue 跳过该次循环

del 删除对象
pass 跳过,占位用
with 常见于with open() as f;上下文管理器,语句执行,触发表达式的__enter__,语句块结束,触发__exit__

デバッグ

assert 调试用 python -O 删除 a=b=0;assert not a is b AssertionError
raise 自定义异常 raise ValueError('a 必须是数字') ValueError: a 必须是数字

その他

__peg_parser__ 
SyntaxError: You found it! (Python 3.9)
Python父曾经想做的语法解释器,https://www.linuxprobe.com/use-peg-parser.html

マップのソースコード

の種類

# 类型

## 常见类型

### 布尔 bool True、False

### 数字Numeric

#### 整数int 无限精度

#### 浮点数float 双精度、inf、-inf、nan(不区分大小写)

#### 复数complex 1.1+1.1j

### 序列 Sequence

#### 列表 list 可变序列

#### 元组 tuple 不可变列表

#### 范围 range 实现迭代的切片

#### 字符串 str 以高位扩展unicode存储

#### 字节串 bytes 字节字符串

#### 字节数组 bytearray 可变字节串

#### 内存视图 memoryview 切片操作不需要额外消耗内存的字节串

### 集合 Set

#### 集合 set 哈希+元素,可变,规律排序,可数学集合操作

#### 冻结集合 fronzenset 不可变集合

### 映射 Mapping

#### 字典 dict key哈希+key+value,3.6版开始,顺序为输入顺序

## 切片 slice

### 切片概念,可以比较,不可迭代

## 迭代器 Iterator .\_\_iter\_\_() 上述序列、集合、映射

### 生成器 Generator .\_\_next\_\_()

#### enumerate 枚举

#### filter 过滤

#### map 映射

#### reversed 逆序

#### zip 打包

## 上下文管理器 Context Manager .\_\_enter\_\_() .\_\_exit\_\_() open() TextIOWrapper with语句块可调用

## 泛型 list\[i\]事先并不确定其类型

### 标准泛型容器 上述容器 collections的容器、基类 re.Pattern、re.Match

### 特殊泛型 所有参数化泛型都实现了特殊的只读属性 genericalias.\_\_origin\_\_ genericalias.\_\_args\_\_ genericalias.\_\_parameters\_\_

## 其他

### 模块 module from \| import

### 类与类实例 Classes and Class Instances

#### 类 type class c: def f():pass

#### 类实例 c c1=c()

### 函数 function def 独立的语句块 类的内部的函数 c.f

### 方法 method 类实例的函数 c1=c();c1.f

### 代码对象 code .\_\_code\_\_属性 compile('code','file','eval\|exec')

### 类型对象 type type、object、class

### 空对象 NoneType None,可当作特殊的数值,未定义返回的函数的返回值

### 省略符对象 ellipsis Ellipsis,...,l.append(l) \[1, 2, 3, \[...\]\]

### 未实现对象 NotImplementedType NotImplemented,二元多态函数,若某多态函数\_\_add\_\_(a,b)不存在,查找另一个多态函数\_\_add\_\_(b,a)

### 内部对象 参阅8.10 types --- 动态类型创建和内置类型名称,内容不少

## 特殊属性

### object.\_\_dict\_\_ 一个字典或其他类型的映射对象,用于存储对象的(可写)属性

### instance.\_\_class\_\_ 类实例所属的类

### class.\_\_bases\_\_ 由类对象的基类所组成的元组

### definition.\_\_name\_\_ 类、函数、方法、描述器或生成器实例的名称

### definition.\_\_qualname\_\_ 类、函数、方法、描述器或生成器实例的标准名称

### class.\_\_mro\_\_ 此属性是由类组成的元组,在方法解析期间会基于它来查找基类

### class.mro() 此方法可被一个元类来重载,以为其实例定制方法解析顺序。它会在类实例化时被调用,其结果存储于\_\_mro\_\_ 之中

### class.\_\_subclasses\_\_() 每个类都保留一个对其直接子类的弱引用列表 int.\_\_subclasses\_\_() [bool, <enum 'IntEnum'>, <enum 'IntFlag'>, sre_constants._NamedIntConstant, subprocess.Handle]

おすすめ

転載: blog.csdn.net/jhsxy2005/article/details/113998157