2014-04-16 34 views
0

我正在嘗試爲整數創建nan值。我正在考慮的設計如下。 我需要創建和類定義頭部isnan拉姆達功能,但它返回一個錯誤類頭中的lambda函數

import numpy as np 

class Integer(object): 
    type = int 
    nan = -1 
    isnan = lambda val: val==-1 
    def __new__(cls, value): 
     return cls.type(value) 

class Float(object): 
    type = float 
    isnan = lambda val: np.isnan(val) 
    def __new__(cls, value): 
     return cls.type(value) 

但它返回一個錯誤

>> Integer.isnan(1) 
>> Traceback (most recent call last): 
>> File "<stdin>", line 1, in <module> 
>>TypeError: unbound method <lambda>() must be called with Integer instance as first argument (got  int instance instead) 

回答

2

的問題是,你isnan功能被視爲由Python實例的方法。即使您將它們「解除綁定」,Python 2仍會執行類型檢查以確保方法的第一個參數是該類的一個實例(例如self)。在Python 3中,未綁定的方法已被丟棄,並且您的代碼可以正常工作。

您可以通過staticmethod解決此通過將lambda函數:

isnan = staticmethod(lambda val: val == -1) 

或者你可以使用常規的函數定義,staticmethod作爲裝飾:

@staticmethod 
def isnan(value): 
    return val == -1 

請注意,如果您使您的類繼承其type值,您可以將其稱爲isnan作爲實際實例方法:

class Integer(int): 
    # no __new__ needed 
    def isnan(self): 
     return self == -1 

這將讓你打電話Integer(5).isnan(),而不是你在當前的代碼做什麼。

最後一條建議:不要使用type作爲變量名稱,因爲它已經是內置的type類的名稱。使用它作爲類屬性並不是什麼壞事,因爲它會作爲一個變量(它會影響內置),但它仍然可能會令人困惑。

1

你需要使它成爲一個靜態方法。有兩種選擇:

class Integer(object): 
    type = int 
    nan = -1 

    @staticmethod 
    def isnan(v): 
     return v == -1 

    isnan_lambda = staticmethod(lambda v: v == -1) 

    def __new__(cls, value): 
     return cls.type(value) 

print Integer.isnan(5) 
print Integer.isnan(5)