5 回答

TA貢獻1817條經驗 獲得超6個贊
使用裝飾器或閉包
def my_yeehaw(result):
def yeehaw():
if some_bool:
return 'yeehaw'
return result
return yeehaw
a = my_yeehaw('a')
b = my_yeehaw('b')

TA貢獻1804條經驗 獲得超8個贊
您可以使用接受 a 的 lambda。bool以及條件為假時返回的默認值:
check = lambda condition, default: 'yeehaw' if condition else default
def a():
return check(condition, 'a')
def b():
return check(condition, 'b')

TA貢獻1809條經驗 獲得超8個贊
我是 python 的新手,但我認為您可以使用默認參數根據傳遞給函數的內容發送 a 或 b。
def a(x='a'):
if condition: #where condition can be True or False
return 'yeehaw'
return x

TA貢獻1864條經驗 獲得超2個贊
(注意:我的命名不是最好的,考慮到same_bool可以更好地調用該函數identical_if_block(...)以遵循您的示例而且我還假設 bool_ 是一個參數,盡管它可以作為全局參數使用。但不像bool任何函數對象那樣,總是真實的
>>> bool(bool)
True
)
使用一個函數,只要它不需要返回 falsies。
def same_bool(bool_):
" works for any result except a Falsy"
return "yeehaw" if bool_ else None
def a(bool_):
res = same_bool(bool_)
if res:
return res
return 'a'
def b(bool_, same_bool_func):
#you can pass in your boolean chunk function
res = same_bool_func(bool_)
if res:
return res
return 'b'
print ("a(True):", a(True))
print ("a(False):", a(False))
print ("b(True, same_bool):", b(True,same_bool))
print ("b(False, same_bool):", b(False,same_bool))
輸出:
a(True): yeehaw
a(False): a
b(True, same_bool): yeehaw
b(False, same_bool): b
如果確實需要偽造,請使用特殊的保護值
def same_bool(bool_):
" works for any result"
return False if bool_ else NotImplemented
def a(bool_):
res = same_bool(bool_)
if res is not NotImplemented:
return res
return 'a'
您也可以輸入"a","b"因為它們是恒定的結果,但我認為這只是在您的簡化示例中。
def same_bool(bool_, val):
return "yeehaw" if bool_ else val
def a(bool_):
return same_bool(bool_, "a")

TA貢獻1777條經驗 獲得超3個贊
我最終喜歡上了裝飾器語法,因為包含重復條件邏輯的函數還有很多其他功能:
# `function` is the decorated function
# `args` & `kwargs` are the inputs to `function`
def yeehaw(function):
def decorated(*args, **kwargs):
if args[0] == 7: return 99 # boolean check
return function(*args, **kwargs)
return decorated
@yeehaw
def shark(x):
return str(x)
shark(7)
添加回答
舉報