给定:
variableX = 5
someValueY = 6
假设您想要分配给 variableX
variableX
的最大值和someValueY
:
variableX = max(variableX, someValueY)
我不止一次地认为拥有这样的东西会很好:
variableX max= someValueY
相当于+=
以及其他赋值运算符。
这是一个好主意吗?它已经存在了吗?这不是Pythonic吗?
最佳答案
根据 language reference ,“增强作业”:
is the combination, in a single statement, of a binary operation and an assignment statement
(强调我的)。 max
不是二元运算(它需要任意数量的位置参数加上 key
关键字参数),因此您建议的运算符将与现有套件不一致。您可能还需要 min=
,但是 the other built-in functions 怎么样? ?
在实现层面,请注意,该提案意味着为 Python 代码的解析添加一整层复杂性;如果名称恰好是 max
(或 min
,或您想要提供的任何其他内容)或 any,则解析时会出现一些异常name 将以同样的方式处理,即:
foo func= bar
只是语法糖:
foo = func(foo, bar)
(或 func(bar, foo)
;如果函数不是 commutative 怎么办?)
在评论中,您提到 x max= y, z
将变为 x = max(x, y, z)
,因此第二个参数是一个元组被解压,例如:
foo func= bar
将被翻译为:
foo = func(foo, *bar)
(这意味着单个值需要尾随逗号:x max= y,
),或者我们正在实现更多新语法。
这在实现、测试和维护方面都需要付出很大的努力(更不用说初学者在阅读Python代码之前还需要学习的另一件事)。向语言添加新语法必须始终具有非常强大的情况,并且根据 the Zen of Python (导入此
):
There should be one-- and preferably only one --obvious way to do it.
“一个明显的方法”是现有语法,foo = func(foo, bar)
。这不适用于现有套件,因为根据 relevant PEP
The idea behind augmented assignment in Python is that it isn't just an easier way to write the common practice of storing the result of a binary operation in its left-hand operand, but also a way for the left-hand operand in question to know that it should operate `on itself', rather than creating a modified copy of itself.
为了将其应用于 max=
,我们现在必须允许对象实现例如__imax__
(参见 __iadd__
for +=
),这意味着还有一个常规的 __max__
方法,并可能导致到任意的 __func__ 和 __ifunc__ 方法,这是另一种蠕虫病毒。我想得越多,这个想法就越糟糕……
在类中,您可以使用描述符来实现此目的,以设置特定属性的最大值和最小值;参见例如Implementing a decorator to limit setters .
关于python - Python 中的最小或最大赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764828/