2016-09-13 38 views
2

下面是爲了裝飾用品脫一個類方法的非常簡單的例子一個類的方法,無法使用裝飾品脫單元

from pint import UnitRegistry 

ureg = UnitRegistry() 
Q_ = ureg.Quantity 

class Simple: 
    def __init__(self): 
    pass 

@ureg.wraps('m/s', (None, 'm/s'), True) 
def calculate(self, a, b): 
    return a*b 

if __name__ == "__main__": 
    c = Simple().calculate(1, Q_(10, 'm/s')) 
    print c 

該代碼產生以下ValueError異常。

Traceback (most recent call last): 
    c = Simple().calculate(1, Q_(10, 'm/s')) 
    File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 167, in wrapper 
    File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 118, in _converter 
    ValueError: A wrapped function using strict=True requires quantity for all arguments with not None units. (error found for m/s, 1) 

在我看來,這裏的問題可能與類的實例傳遞給品脫裝飾。有沒有人有解決這個問題的方法?

回答

1

我認爲錯誤信息很清楚。 In strict mode all arguments have to be given as Quantity 但你只給出第二個參數。

你要麼給第一個參數爲Quantity

if __name__ == "__main__": 
    c = Simple().calculate(Q_(1, 'm/s'), Q_(10, 'm/s')) 
    print c 

或禁用嚴格模式,我相信這是你在找什麼。

... 
    @ureg.wraps('m/s', (None, 'm/s'), False) 
    def calculate(self, a, b): 
     return a*b 

if __name__ == "__main__": 
    c = Simple().calculate(1, Q_(10, 'm/s')) 
    print c 
1

感謝您的回答。保持嚴格模式,你的第一個答案產生一個輸出,即使第一個參數也是一個點數。但是,輸出的單位包括包裝器中指定的輸出單位與第一個參數的單位的乘積,這是不正確的。

溶液只是增加另一個「無」到包裝紙以考慮類實例,即

@ureg.wraps('m/s', (None, None, 'm/s'), True) 
def calculate(self, a, b): 
    return a*b