簡體   English   中英

python函數參數執行

[英]python function parameter execution

伙計們,什么是蟒蛇執行語句,直到必要的正確方法。

可以說我有一個執行指數api補償的函數:

def exponential_backoff_task(config, task, description):
    retry_count = config.get( 'retry_count', 5 )
    api_backoff_initial_msec = config.get( 'api_backoff_initial_msec', 200)
    print 'Running api-backoff task: %s, retry_count: %d, initial_backoff: %d' % (description, retry_count, api_backoff_initial_msec)
    result = None
    for r in range(retry_count):
        try:
            result = task
        except boto.exception.BotoServerError:
            delay_msec = (2 ** r) * api_backoff_initial_msec
            print 'Exponential backoff, retry %d for %d msecs...' % (r, delay_msec)
            time.sleep(delay_msec/1000)
            continue
        except:
            raise
    return result


def foo():
    all_instances = exponential_backoff_task(config, conn.get_all_dbinstances(), 'foo'))

在這種情況下, conn.get_all_instances()在調用函數時執行,而不是在exponential_backup函數內部執行

謝謝!

好吧,不要在傳入時調用它,而僅在需要時才調用它:

from functools import partial

def exponential_backoff_task(config, task_fn, description):
    retry_count = config.get('retry_count', 5)
    api_backoff_initial_msec = config.get('api_backoff_initial_msec', 200)
    print 'Running api-backoff task: %s, retry_count: %d, initial_backoff: %d' % (description, retry_count, api_backoff_initial_msec)
    result = None
    for r in range(retry_count):
        try:
            # Call the function that got passed in
            result = task_fn()
        except boto.exception.BotoServerError:
            delay_msec = (2 ** r) * api_backoff_initial_msec
            print 'Exponential backoff, retry %d for %d msecs...' % (r, delay_msec)
            time.sleep(delay_msec / 1000)
            continue
        except:
            raise
    return result


def foo():
    # Note the missing parens: here you're just passing in the function
    all_instances = exponential_backoff_task(config, conn.get_all_dbinstances, 'foo')

編輯 :要在函數中預定義一些參數,可以使用partial ,可以接受函數將參數應用到該函數,然后使用已應用的那些參數返回一個新函數,這是一個示例:

from functools import partial

def f(a, b):
    print a
    print b

g = partial(f, a=1, b=2)

g()

此打印

1
2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM