亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在多個函數中包含相同的 if 塊?

如何在多個函數中包含相同的 if 塊?

MMTTMM 2023-03-22 14:03:01
很抱歉問這樣一個基本問題,但是包含可以有條件地返回多個函數的相同 if 塊的 Pythonic 方法是什么?這是我的設置:def a():  if bool:    return 'yeehaw'  return 'a'def b():  if bool:    return 'yeehaw'  return 'b'我想從這兩個函數中分解出共同的條件,但我不確定該怎么做。
查看完整描述

5 回答

?
慕的地6264312

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')


查看完整回答
反對 回復 2023-03-22
?
胡說叔叔

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')


查看完整回答
反對 回復 2023-03-22
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

我是 python 的新手,但我認為您可以使用默認參數根據傳遞給函數的內容發送 a 或 b。


def a(x='a'):

    if condition: #where condition can be True or False

        return 'yeehaw'

    return x


查看完整回答
反對 回復 2023-03-22
?
慕斯王

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")


查看完整回答
反對 回復 2023-03-22
?
慕森王

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)


查看完整回答
反對 回復 2023-03-22
  • 5 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號