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
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-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)