@geekpi
https://linux.cn/article-13477-1.html
This commit is contained in:
Xingyu Wang 2021-06-12 11:55:41 +08:00
parent 40833d7898
commit fea8df8df2

View File

@ -3,40 +3,40 @@
[#]: author: (Moshe Zadka https://opensource.com/users/moshez)
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-13477-1.html)
Python 3.9 如何修复装饰器并改进字典
======
探索最近版本的 Python 的一些有用的特性。
![Python in a coffee cup.][1]
这是关于首次出现在 Python 3.x 版本中的特性的系列文章中的第十篇其中一些版本已经发布了一段时间。Python 3.9 在 2020 年首次发布,具有很酷的新特性,但仍未被充分利用。下面是其中的三个。
> 探索最近版本的 Python 的一些有用的特性。
![](https://img.linux.net.cn/data/attachment/album/202106/12/115315xrnd4evse8uzpi8i.jpg)
这是 Python 3.x 首发特性系列文章中的第十篇其中一些版本已经发布了一段时间。Python 3.9 在 2020 年首次发布,具有很酷的新特性,但仍未被充分利用。下面是其中的三个。
### 添加字典
假设你有一个 “defaults” 字典,而你想更新它的参数。在 Python 3.9 之前,最好的办法是复制 defaults 字典,然后使用 `.update()` 方法。
假设你有一个 `defaults` 字典,而你想更新它的参数。在 Python 3.9 之前,最好的办法是复制 `defaults` 字典,然后使用 `.update()` 方法。
Python 3.9 为字典引入了联合运算符:
```
defaults = dict(who="someone", where="somewhere")
params = dict(where="our town", when="today")
defaults | params
```
```
` {'who': 'someone', 'where': 'our town', 'when': 'today'}`
```
注意,顺序很重要。在这种情况下,来自 `params``where ` 值覆盖了默认值,因为它应该如此。
```
{'who': 'someone', 'where': 'our town', 'when': 'today'}
```
注意,顺序很重要。在这种情况下,正如预期,来自 `params``where` 值覆盖了默认值。
### 删除前缀
如果你用 Python 做了临时的文本解析或清理,你会写出这样的代码:
如果你用 Python 做临时的文本解析或清理,你会写出这样的代码:
```
def process_pricing_line(line):
@ -44,25 +44,27 @@ def process_pricing_line(line):
return line[len("pricing:"):]
return line
process_pricing_line("pricing:20")
```
```
```
` '20'`
'20'
```
这样的代码很容易出错。例如,如果字符串被错误地复制到下一行,价格就会变成 `0` 而不是 `20`,而且会悄悄地发生。
从 Python 3.9 开始,字符串有了一个 `.lstrip()` 方法:
```
"pricing:20".lstrip("pricing:")
```
```
`"pricing:20".lstrip("pricing:")`[/code] [code]` '20'`
'20'
```
### 任意的装饰器表达式
以前,关于装饰器中允许哪些表达式的规则没有得到充分的记录,而且很难理解。例如:虽然
以前,关于装饰器中允许哪些表达式的规则没有得到充分的说明,而且很难理解。例如:虽然
```
@item.thing
@ -72,7 +74,6 @@ def foo():
是有效的,而且:
```
@item.thing()
def foo():
@ -81,7 +82,6 @@ def foo():
是有效的,相似地:
```
@item().thing
def foo():
@ -92,7 +92,6 @@ def foo():
从 Python 3.9 开始,任何表达式作为装饰器都是有效的:
```
from unittest import mock
@ -102,10 +101,10 @@ item = mock.MagicMock()
def foo():
pass
print(item.return_value.thing.call_args[0][0])
```
```
```
` <function foo at 0x7f3733897040>`
<function foo at 0x7f3733897040>
```
虽然在装饰器中保持简单的表达式仍然是一个好主意,但现在是人类的决定,而不是 Python 分析器的选择。
@ -121,7 +120,7 @@ via: https://opensource.com/article/21/5/python-39-features
作者:[Moshe Zadka][a]
选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出