kle*_*len 3 python parsing operator-keyword
例如,这些在运算符模块中定义,可以这样使用:
import operator
print operator.__add__ # alias add -> +
print operator.__sub__ # alias sub -> -
print operator.__and__ # alias and_ -> &
print operator.__or__ # alias or_ -> |
Run Code Online (Sandbox Code Playgroud)
那么什么是相当于and和or?
print operator."and ?????" # should be boolean-and
print operator."or ????" # should be boolean-or
Run Code Online (Sandbox Code Playgroud)
这些不存在.你能做的最好的事就是用lambda代替它们:
band = (lambda x,y: x and y)
bor = (lambda x,y: x or y)
Run Code Online (Sandbox Code Playgroud)
原因是你无法实现完整的行为,and或者or因为它们可能会短路.
例如:
if variable or long_fonction_to_execute():
# do stuff
Run Code Online (Sandbox Code Playgroud)
如果variable是的话True,long_fonction_to_execute永远不会被调用,因为Python知道而不是or必须返回True.这是一个优化.在大多数情况下,这是一个非常理想的功能,因为它可以节省大量无用的处理.
但这意味着你不能使它成为一个功能:
例如:
if bor(variable, long_fonction_to_execute()):
# do stuff
Run Code Online (Sandbox Code Playgroud)
在这种情况下,long_fonction_to_execute甚至在评估之前就会调用它.
幸运的是,鉴于您使用生成器和列表推导这一事实,您很少需要类似的东西.
| 归档时间: |
|
| 查看次数: |
297 次 |
| 最近记录: |