Python 查漏补缺

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wkb342814892/article/details/81294891

Python 查漏补缺

f-string

name = "allen"
f = "My name is {name}"
value = 1.23456
f = "Value is {value:5.3}" # 5 for width, 3 for precision

这让字符串的格式化变得更加方便了,并且速度快于format,在特殊场景下应该会有非常不错的性能表现

类型注解

from typing import List
test_list: List[int] = []

def test(a: int, b: float=1.23) -> str:
    return "Hello world"

# 需要注意,类型注解只提供解释性注释,没有实际校验功能,当然,也有第三方库提供校验
pip install mypy
mypy test.py # 如果类型都符合,则不会有任何输出,否则就会给出错误报警
# test.py:6: error: Argument 1 to "append" of "list" has incompatible type "float"; expected "int"

dataclass

from dataclasses import dataclass, InitVar 
# InitVar配合HootInit使用

@dataclass
class C:
    a: float
    b: float
    c: float = field(init=False)

    def __post_init__(self): # 这里可以写对参数的额外解析
        self.c = self.a + self.b

# 有位老哥写的很详细,建议看看:https://www.kawabangga.com/posts/2959

猜你喜欢

转载自blog.csdn.net/wkb342814892/article/details/81294891