python不同版本常用功能差异

py3.5

  • 列表(*)、字典(**)解包操作符
print(*[1], *[2], 3, *[4, 5])


def fn(a, b, c, d):
    print(a, b, c, d)


fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})

"""************************************************"""

*range(4), 4

[*range(4), 4]

{*range(4), 4, *(5, 6, 7)}

{'x': 1, **{'y': 2}}
  • 函数注解  (1. 方便程序员查看,2. IDE的设计者可以用来做代码检查。)

py3.6

  • 格式化字符串 f-字符串
name = "Fred"
str_ = f"He said his name is {name}."

print(str_) # He said his name is Fred
  • 变量注解
"""添加变量注释后会添加到__annotations__中"""
primes: List[int] = []

captain: str  # Note: no initial value!

class Starship:
    stats: Dict[str, int] = {}

n   : int                 # n为int型变量,没有赋值
n2  : int     = 10        # n2为int型变量,赋值为10
r   : str                 # r为str型变量,没有赋值
r2  : str     = 'hello'   # r2为str型变量,赋值为hello
v   : float               # v为float型变量,没有赋值
v1  : float   = 3.14      # v1为float型变量,赋值为3.14

py3.7

  • 类型标注延迟求值
# 不带类型注解
def foo(bar, baz):
    pass

#def foo(bar: str, baz: int)-> int:
#    return baz

# 标注延迟求值
from __future__ import annotations

py3.8

  • 海象运算符  ( := 可在表达式内部为变量赋值)
"""海象运算符, :返回值、= 赋值 ,赋值后返回"""

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

if a:=1>0:
    print(a)  # 1
  • 仅限位置形参   /
  • 仅限关键字参数 *
# / : 函数形参语法 / 用来指明某些函数形参必须使用仅限位置而非关键字参数的形式
def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

# 形参 a 和 b 为仅限位置形参,c 或 d 可以是位置形参或关键字形参,而 e 或 f 要求为关键字形参
f(10, 20, 30, d=40, e=50, f=60)
  •  f-字符串支持 = 用于自动记录表达式和调试文档
# 增加 = 说明符用于 f-string。 形式为 f'{expr=}' 的 f-字符串将扩展表示为表达式文本,加一个等于号,再加表达式的求值结果。
print(f'{theta=}  {cos(radians(theta))=:.3f}') # theta=30  cos(radians(theta))=0.866

# 通常的 f-字符串格式说明符 允许更细致地控制所要显示的表达式结果:
>>> delta = date.today() - member_since
>>> f'{user=!s}  {delta.days=:,d}'
'user=eric_idle  delta.days=16,075'

>>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
theta=30  cos(radians(theta))=0.866

py3.9

  • 字典合并与更新运算符
>>> x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> x | y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
>>> y | x
{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}
  • 新增用于移除前缀和后缀的字符串方法
str.removeprefix(prefix, /)

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'


str.removesuffix(suffix, /)

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
  • 标准多项集中的类型标注泛型
def greet_all(names: list[str]): #  -> None
    for name in names:
        print("Hello", name)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值