簡體   English   中英

跨多個函數檢查參數的優雅方式

[英]Elegant way to check arguments across multiple functions

我正在處理一些包含大量函數的 python 代碼。 其中許多需要相同的輸入參數集。

我需要對輸入參數的值進行一些限制。 如果它們位於某個規定范圍之外,那么我想提出一條錯誤消息。 理想情況下,我希望在沒有大量重復代碼的情況下執行此操作。 下面是我正在嘗試做的一個簡化示例:

def check_positive(T):
    # Temperatures must be provided in kelvin
    if T < 0:
        print('Temperatures are in K, negative values not allowed!')

def double(T):
    check_positive(T)
    return 2*T

def treble(T):
    check_positive(T)
    return 3*T

T = -2
print(double(T))

T = 100
print(treble(T))

在我的實現中,每個函數都需要調用 check_positive 函數。 是否有更優雅的方式在 python 中實現相同的行為?

聽起來像是python 裝飾器的完美用例!

編輯:

from functools import wraps

def check_positive(func):
    
    @wraps(func)    
    def wrapper(*T):
        # Temperatures must be provided in kelvin
        if T[0] < 0:
            print('Temperatures are in K, negative values not allowed!')
            raise ValueError  # optional
        return func(T[0])
    return wrapper

@check_positive
def double(T):
    return 2*T

...

可以在此處使用裝飾器:

def check_positive(func):
    def wrapper(*args, **kw):
        if args[0] < 0:
            print('Temperatures are in K, negative values not allowed!')
        return func(*args, **kw)
    return wrapper


@check_positive
def double(T):
    return 2*T

@check_positive
def treble(T):
    return 3*T

T = -2
print(double(T))

T = 100
print(treble(T))

輸出:

Temperatures are in K, negative values not allowed!
-4
300

如果傳遞了負值,您可以進一步更改裝飾器以返回異常 - 在這里我們只打印您的示例中的語句。

暫無
暫無

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

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