深度解析Python关键字:掌握核心语法的基石(新版本35+4)-LMLPHP

目录

关键字 keyword

关键字列表

kwlist

softkwlist 

关键字分类 

数据类型

True、False

None

运算类型

and、or、not

in

is

模块导入

import

辅助关键字

from、as

上下文管理

with

占位语句

pass

流程控制

if、elif、else

for

while

break、continue

类和函数

class

def

lambda

return

yeild

变量相关

global

nonlocal

del

异常处理

try、except、finally

raise

assert

异步函数

async、await

软关键字

match、case、_

type

总结


关键字 keyword

Python关键字keyword,也被称为“保留字”,是有特殊功能的标识符,不允许开发者自定义。

本文将带你一起探索Python中的各类关键字及其应用场景,在python执行函数help("keywords")就能得到所有关键字的列表:

>>> help("keywords")
Here is a list of the Python keywords.  Enter any keyword to get more help.

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

当前python最新版本号为3.12,目前有35个关键字,比旧版本多了2个与异步编程相关的关键字;另外还多了四个所谓的“softkeyword”,导入keyword库,除了有kwlist还多了一个softkwlist。

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', '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']
>>> keyword.softkwlist
['_', 'case', 'match', 'type']
>>> len(keyword.kwlist)
35
>>> len(keyword.softkwlist)
4

keyword库还有两个判断函数,用法如下:

>>> keyword.iskeyword('async')
True
>>> keyword.iskeyword('match')
False
>>> keyword.issoftkeyword('_')
True
>>> keyword.issoftkeyword('await')
False

想获取所有关键字的英文帮助,可用以下代码实现:

import sys, keyword

out = sys.stdout #保存标准输出流

for i, kw in enumerate(keyword.kwlist+keyword.softkwlist, 1):
    fn = ("%02d" % i) + "." + kw + ".txt"
    with open(fn, 'w') as f:
    	sys.stdout = f
    	help(kw)
 
sys.stdout = out #恢复标准输出流
 
print("end")

关键字列表

kwlist

softkwlist 


关键字分类 

数据类型

True、False

布尔类型数据

>>> int(True)
1
>>> int(False)
0
>>> isinstance(True, type(False))
True

None

None类型数据

>>> isinstance(None, type(None))
True
>>> type(None)
<class 'NoneType'>

运算类型

and、or、not

逻辑运算符:与、或、非

in

成员运算符,用于判断对象是否包含于序列类型(如列表、元组、字符串)或其他可迭代对象(如集合、字典的键)中。

is

比较运算符,用于检查两个对象是否引用同一个内存地址,即判断它们是否是同一个对象实例。

A is B 相当于 id(A) == id(B)

模块导入

import

用于导入模块,import 模块名

也可以与from或as结合使用

from 模块名 import 具体模块方法、函数、属性等

import 模块名 as 模块别名

也可以使用 from ... import ... as ...

辅助关键字

from、as

这2个只能配合其他关键字一起使用,没有单独的功能,除了import语句中使用它俩外,还有:

with ... as ... 、 yield from ...

上下文管理

with

with语句块,实现上下文管理协议,确保在执行代码块前后自动调用初始化和清理操作。比如,在处理文件时,可以安全地打开和关闭文件,即使发生异常也能保证资源被释放,语句块结束会自动关闭已打开的文件对象。

with open('example.txt', 'r') as file:  
    content = file.read()  
    # 在这里处理文件内容  

# 文件已关闭

除了文件操作,还能在网络请求、 数据库连接、线程锁等场景中使用:

import socket  
  
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:  
    s.connect(("www.example.com", 80))  
    s.sendall(b"GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n")  
    response = s.recv(4096)  

# 连接已关闭
print(response)
import sqlite3

with sqlite3.connect('example.db') as conn:
    cursor = conn.cursor()
    # 执行 SQL 语句
    pass

# 数据库已关闭

with语句块还能嵌套使用:

也能写成等效的语句: with A() as a, B() as b: pass

占位语句

pass

什么都不做,临时占个位置,比如用在空类、空函数、空语句块等等。

流程控制

if、elif、else

条件语句,if 可以单独使用,还可以搭配elif和else使用,如 if-else, if-elif-else, if-elif-elif-else

else还能和循环语句或异常捕获语句一起使用,如 for-else, while-else, try-except-else

if和else还能用在类似三元操作符的结构中,如:

>>> x = 100
>>> 1 if x>0 else 0
1

for

for 循环语句

能通与 in 搭配使用 for ... in iterable:,也能与 else 结合使用。

while

while 循环语句

也能与 else 结合使用,while-else 和 for-else 一样在非break中断时循环结束后,继续执行else后的语句。

break、continue

循环中断和继续,区别是终止整个循环和退出单次循环。

注:if 和 for 搭配使用中列表、字典等的推导式中,如:

>>> [i for i in 'abcdef' if 'a'<i<'e']
['b', 'c', 'd']

类和函数

class

定义类

def

定义函数

lambda

定义匿名函数

return

函数终止并返回值。

yeild

函数终止并返回一个生成器

还可以与from连用,yeild from iterable 表示引用一个可迭代对像的值并返回生成器。

变量相关

global

声明全部变量

# 全局变量定义
global_var = 0

def update_global():
    # 在函数内部声明 global_var 是全局变量
    global global_var
    # 修改全局变量的值
    global_var += 1
    print(f"Inside function: {global_var}")

# 调用函数前查看全局变量的值
print("Before function call:", global_var)

# 调用函数
update_global()

# 函数调用后再次查看全局变量的值,会发现它已被修改
print("After function call:", global_var)
nonlocal

用于定义在嵌套函数中引用外部函数的变量。

def outer_function():
    outer_var = 5

    def inner_function():
        nonlocal outer_var
        outer_var = 15
        print("内部函数访问外部变量:", outer_var)

    inner_function()
    print("外部函数访问内部变量:", outer_var)

outer_function()

 输出结果:

上述的代码如果注释掉nonlocal outer_var这一行,输出结果变为:

del

用于删除变量、列表元素、字典元素或其他可变对象的引用。

x = 10
print(x)  # 输出:10

del x

try:
    print(x)
    # 此时尝试访问 x 将引发 NameError,因为 x 已被删除
except NameError as e:
    print(e)

输出:

异常处理

try、except、finally

捕获异常语句,也能与 else 一起使用,常用的结构有:

try-except;try-except-else;try-except-finally;try-except-else-finally

具体使用方法见以下实例中的注释:

x = 0

try:  
    # 尝试执行的代码  
    y = 1 / x  # 这里会引发一个ZeroDivisionError  
except ZeroDivisionError as e:  
    # 当发生ZeroDivisionError异常时执行的代码  
    print("发生了除以零的错误,错误信息为:", e)  
else:  
    # 如果try代码块中的代码没有引发任何异常,则执行此代码块  
    print("try代码块中的代码成功执行")  
finally:  
    # 不论是否发生异常,都会执行的代码  
    print("finally代码块中的代码总是会执行")

执行结果:

raise

异常抛出语句,可用于代码测试,但出错就会中断代码运行。

def validate_email(email):  
    if "@" not in email:  
        raise ValueError("无效的电子邮件地址!")  
    else:  
        print("电子邮件地址有效")  
  
validate_email("test@example")  # 输出: 电子邮件地址有效  
validate_email("test")  # 抛出ValueError: 无效的电子邮件地址!

也可以通过参数传递抛出系统定义的异常,以扩展异常捕获语句。

def handle_exception(e):
    # 对异常进行一些处理后,选择再次引发它
    print("Handling the exception...")
    raise e  # 再次引发原来的异常

try:
    x = 1/0
except ZeroDivisionError as e:
    handle_exception(e)
assert

断言语句,用于判断变量或者表示式的值是否为真;通常用于代码测试,且不会中断代码运行。

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        assert len(self.items) > 0, "Cannot pop from an empty stack."
        return self.items.pop()

stack = Stack()
stack.push('item1')

# 正常情况下的弹出操作
popped_item = stack.pop()

# 尝试从空栈中弹出元素,将触发AssertionError
try:
    popped_item_empty = stack.pop()
except AssertionError as e:
    print(f"Assertion error: {e}")

print("End")

输出:

异步函数

async、await

python3.5新增的关键字,用于异步函数的定义声明和挂起执行。

import asyncio

def fib(n):
    if n<600:
        n1 = n2 = 1
        for _ in range(2,n):
            n1,n2 = n1+n2,n1
        return n1
    t = n//2
    if n%2:
        return fib(t+1)**2 + fib(t)**2
    else:
        return fib(t+1)**2 - fib(t-1)**2
 
def Fib(n):
    return fib(n)
 
async def asyncFib(n):
    res = Fib(n)
    print(res)
 
async def main():
    await asyncio.gather(*tasks)
 
if __name__ == "__main__":
    parms = [500, 2000, 10000]
    tasks = [asyncFib(p) for p in parms]
    loop = asyncio.run(main())

软关键字

match、case、_

python3.10新增的关键字,用于匹配语句,相当于其它语言中的分支结构switch-case。

之前的python版本中,一直由if...elif...[elif...]else来代替。

def process_data(data):
    match data:
        case 1:
            return "数据为1"
        case 2:
            return "数据为2"
        case 3:
            return "数据为3"
        case _:
            return "未知数据"

print(process_data(1))  # 输出:数据为1
print(process_data(2))  # 输出:数据为2
print(process_data(3))  # 输出:数据为3
print(process_data(4))  # 输出:未知数据
type

判断数据类型

>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> type(1.5)
<class 'float'>
>>> type(1+1j)
<class 'complex'>


总结

Python关键字是一些预定义的标识符,是编程语言内建的具有特殊含义的保留字,它们在语法结构、逻辑控制、错误处理等方面执行特定的操作。作为构成python语言语法结构的核心元素,不可用作变量名、类名或函数名等。理解并熟练运用这些关键字对于编写高质量、易于理解和维护的代码至关重要。Python3.12中共有35+4个关键字,其分类如下:

深度解析Python关键字:掌握核心语法的基石(新版本35+4)-LMLPHP


深度解析Python关键字:掌握核心语法的基石(新版本35+4)-LMLPHP

01-22 07:51