- 类型系统,更方便的类型别名声明方式
简便的类型别名声明
我们可以直接如下定义类型别名
Point = tuple[float, float]
class PointTest:
def __init__(self):
self.point: Point = (0, 0)
在python12中,可以用type
对这种别名进行表示和区分
type Point = tuple[float, float]
class PointTest:
def __init__(self):
self.point: Point = (0, 0)
TypedDict和Unpack的结合:更精准的**kwargs
传参
Python38时引入了TypedDict
,用于显示定义dict的键值类型。
from typing import TypedDict
class Person(TypedDict):
name: str
age: int
def get_author(author: Person):
print(author)
author_data = {'name': 'Yang', 'age': 30, 'gender': 'male'}
get_author(author_data)
然而,若将参数中的author替换为**kwargs
,程序就会报错。
from typing import TypedDict
class Person(TypedDict):
name: str
age: int
# def get_author(author: Person):
# print(author)
def get_author(**kwargs: Person):
print(author)
author_data = {'name': 'Yang', 'age': 30, 'gender': 'male'}
get_author(author_data)
因为,所有的参数就会被当做Person类型,而不是将所有参数当做一个Person的子类。
因此,python3.12提供了Unpack类型。
改进的F-String语法。
可以在F-String中的括号中直接使用双引号。
>>> print(f"This is the author: {"".join(["Y","a","n","g"])}")
This is the author: Yang
另外,还可以使用反斜杠了。
>>> print(f"This is the author:\n{"".join(["Y","a","n","g"])}")
Traceback (most recent call last):
...
File "<input>", line 1
print(f"This is the author:\n{"".join(["Y","a","n","g"])}")
^
SyntaxError: f-string: expecting '}'
now:
>>> print(f"This is the author:\n{"".join(["Y","a","n","g"])}")
This is the author:
Yang
提供Override装饰器,显示声明函数实现覆盖
from typing import override
class Animal:
def speak(self) -> str:
pass
class Dog(Animal):
@override
def speak(self) -> str:
return 'woof'
def walk(self) -> str:
return 'walking'
my_dog: Dog = Dog()
print(my_dog.speak())
# woof
print(my_dog.walk())
报错信息能提供建议
当然,建议仅针对NameError
,ImportError
,SyntaxError
异常