【再回首Python之美】【and-or】危险的and-or,安全的if-else,和安全的and-or
程序员文章站
2022-05-03 10:54:15
...
and-or概念
ret = condition and left or right
一般情况下,所得即所想:
condition为True时,ret等于left;condition为False时,ret等于right
危险的and-or
危险情况,所得非所想,一个栗子:
ret = condition and "" or right,这个语句执行后,期望ret等于"",但是ret等于right!
if-else概念
if-else是安全的,永远所得即所想。下面语句,condition是True,所得left;condition是False,所得right。
if condition:
return left
else:
return right
安全的and-or
ret = (condition and [left] or [right])[0],此语句是安全的,实现了所得即所想。
定义成一个函数实现安全的and-or,以后直接调用此函数就可以。
def safe_and_or(condition, left, right):
return (condition and [left] or [right])[0]
安全的and-or使用了list的两个性质:
1)[""]不是空表
2)[left][0]恒等于left
and-or的必要性
有的函数无法使用if-else,则必须使用and-or,所以研究安全的and-or是有必要的。
示例代码
#ex_and-or.py
self_file = __file__
#and-or,可以实现if-else功效
#使用and-or时,一定严格按照此格式使用
#(condition and [left] or [right])[0]
def safe_if_else(condition, left, right):
if condition:
return left
else:
return right
def safe_and_or(condition, left, right):
return (condition and [left] or [right])[0]
print "\n===conceptual and-or==="
left = "left"
right = "right"
print True and left or right #pass:expect left, result left
print safe_if_else(False, left, right) #pass:expect right, result right
print False and left or right #pass:expect right, result right
print safe_if_else(False, left, right) #pass:expect right, result right
print "\n===wrong dangerous and-or==="
left = "" #dangerous factor
right = "right"
print True and left or right #failed:expect "", but result "right"
print safe_if_else(True, left, right) #pass:expect "", result ""
print "\n===safe and-or==="
left = ""
right = "right"
print safe_and_or(True, left, right) #pass:expect "", result ""
print safe_if_else(True, left, right) #pass:expect "", result ""
print "\n===research [left][0]==="
left = "left"
print type([left]) #<type 'list'>
print [left] #['left']
print type([left][0]) #<type 'str'>
print [left][0] #left
if [left][0] == left:
print "left == [left][0]" #"left == [left][0]"
else:
print "left != [left][0]"
print "\nexit %s" % self_file
编译执行:
(end)
上一篇: QT属性动画