Python 3.7已于2018年6月发布。这个版本带来了许多改进和新特性。下面就让我们来看看Python 3.7带来的变化。
一、格式化字符串字面量(f-strings)
# Python 3.6 name = "Alice" print("Hello, {}".format(name)) # Python 3.7 name = "Alice" print(f"Hello, {name}")
二、async和await成为关键字
# Python 3.6 import asyncio async def async_func(): return "Hello, world!" loop = asyncio.get_event_loop() result = loop.run_until_complete(async_func()) print(result) # Python 3.7 async def async_func(): return "Hello, world!" asyncio.run(async_func())
三、一个新的平行赋值语句
# Python 3.6 a, b, c = [1, 2, 3] # Python 3.7 a, *b, c = [1, 2, 3, 4, 5]
四、dataclasses模块
# Python 3.6 class Point: def __init__(self, x, y): self.x = x self.y = y # Python 3.7 from dataclasses import dataclass @dataclass class Point: x: int y: int
五、time模块的新功能
# Python 3.6 import time start = time.time() time.sleep(1) end = time.time() print(end - start) # Python 3.7 import time start = time.monotonic() time.sleep(1) end = time.monotonic() print(end - start)
六、其他变化
1.引入了contextlib.asynccontextmanager修饰器,用于异步上下文管理器; 2.增加了一些math模块的常用数学常量和函数,如math.isqrt、math.hypot等; 3.os.makedirs现在支持exist_ok参数,以避免抛出FileExistsError异常; 4.random.choices函数可以带权重的随机选择; 5.字典的key列表可以通过一个字典视图(例如键视图或值视图)进行排序。
综上,Python 3.7带来了许多令人期待的改进和新特性,使得Python更加易用、高效和协作。我们期待着更多的Python版本带来更多的惊喜。
上一篇 html标点符号代码
下一篇 jquery 冒号选择器