类型注释
增加代码可读性
from typing import List, Dict, Set, Union, Optional
def add_enter(b: str) -> str:
return b + '\n'
def parse_data(data):
total = 0
for k, vs in data.items():
if k[1]:
for v in vs:
total += v
return total
def parse_data(data: Dict[Tuple[str, int], List[int]):
total = 0
for k, vs in data.items():
if k[1]:
for v in vs:
total += v
return total
可以单独对变量进行注释
data: Dict[int, List[int]] = {1: [2, 2, 2]}
Union:
支持多种数据类型,如Union[int, str]
Optional:
可能为该数据类型,或者为None,如:Optional[int]
备注:Python最新版序列初始化函数可以直接用于注释:如:list、dict、set,可用“|”替换Union。
data: dict[int, list[int]] = {1: [2, 2, 2]}
b: bool | int | str = 0
with语法
增加代码可读性
with open('xxx.txt') as fw:
pass
让类支持with语法
class A:
def __enter__(self):
print(1)
def __exit__(self, exc_type, exc_val, exc_tb):
print(2)
a = A()
with a:
print(3)
with a:
print(4)
vm.login()
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
vm.logout()
with vm:
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
node.run({'command': ['xxx']})
用逻辑关键字简化语句
简化分支语句
and: 左侧语句为False后,不执行右侧,直接返回False
or: 左侧语句为True后,不执行右侧,直接返回True
if a:
print('a != 0')
# 以上语句等效于
a and print('a != 0')
if not a:
print('a == 0')
# 以上语句等效于
a or print('a == 0')
简化赋值语句
示例:想让参数a默认为列表
def func(a = None):
if not a:
a = []
a.append(1)
return a
一个默认参数可能不明显
def func(a = None, b = None, c = None):
if not a:
a = []
if not b:
b = set()
if not c:
c = {}
...
def func(a = None, b = None, c = None):
a = a or []
b = b or set()
c = c or {}
...
标签:node,run,可读性,Python,xxx,语法,int,command,print
From: https://www.cnblogs.com/roundfish/p/18650565