2010-08-08 75 views
0

我有一個Python類,像這樣:有沒有辦法讓班級評估爲數字?

class TAG_Short(NBTTag): 
    def __init__(self, value=None): 
     self.name = None 
     self.value = value 

    def __repr__(self): 
     return "TAG_Short: %i" % self.value 

這個標籤是在運行時填寫的,但我也希望能夠使用它像:

mytag = TAG_Short(3) 
mycalc = 3 + (mytag % 2)/mytag 

有什麼方法我需要添加到標籤以允許我將其用作有效的數字類型?

回答

3

我see--你想是有東西像一個__as_number__方法,你可以在TAG_Short定義,這將讓你返回一個數字,然後在任何地方使用,其中一個ValueError會即將提高。我不知道是否有任何方法可以做到這一點,而不是自己實現這個元功能。

什麼你可以做的是定義__add____radd____mul____rmul__等(必須,如果你想你的對象,真正表現得像在任何情況下一些定義每一個數字的方法),並有他們每個人的回報使用您認爲是TAG_Short對象的數字表示形式進行所需操作的結果。如果你發現自己經常這樣做,你可以考慮實現你描述的元功能(或者首先尋找一個穩定的實現來重用)。在Python中這是非常可行的。我認爲它甚至可能那麼容易,因爲一個良好的,老式的類從(未測試的代碼如下)繼承,東西有點像:

class AbstractNumberImpersonator: 
    # child classes should define method .to_number() 
    def __add__(self, other): 
     return self.to_number() + other 
    __radd__ = __add__ 
    def __mul__(self, other): 
     return self.to_number() * other 
    __rmul__ = __mul__ 
    # etc - implement all the others in the same fashion 

然後,你可以這樣做:

class TAG_Short(NBTTag,AbstractNumberImpersonator): 
    def __init__(self, value=None): 
     self.name = None 
     self.value = value 

    def __repr__(self): 
     return "TAG_Short: %i" % self.value 

    def to_number(self): 
     return self.value 
+0

哇,是的,這絕對是一個更好的解決方案,因爲我有一些需要應用的標籤。 – Thomas 2010-08-11 06:24:12

4

你必須重載一些操作符。對於你給出的例子,這些都是方法,你應該重載:

def __add__(self, other): 
    return self.value + other 

def __mod__(self, other): 
    return self.value % other 

def __rdiv__(self, other): 
    return other/self.value 

,瞭解更多信息,請參見this guide

+0

做**不**忘記做這個:'__radd__ = __add__',等等。 – jcao219 2010-08-08 05:55:35

+0

感謝人,我希望有一個更簡單的方法(如使用__repr__進行自動字符串轉換),但這也起作用。 – Thomas 2010-08-08 16:03:42

1

是。過載添加方法並使其行爲適當。