2014-01-14 19 views
1

美好的一天! 我想在Python裏面存儲的地圖瓷磚類,如python的方式來使整數類與額外的數據

map = [[WorldTile() for _ in range(10)] for _ in range(10)] 

我創建

class WorldTile: 
    def __init__(self, val): 
     self.resource = val 
     self.objects = dict() 

    def __repr__(self): 
     return self.resource 

    def __str__(self): 
     return '%s' % (str(self.resource)) 

    def __cmp__(self, other): 
     return cmp(self.resource, other) 

    def __add__(self, other): 
     self.resource += other 
     return self.resource 

    def __sub__(self, other): 
     self.resource -= other 
     return self.resource 

類,但出亂子。 i'l嘗試

x = WorldTile.WorldTile(7) 
print type(x), id(x), x 
print x > 2, x < 5, x > 0 
#x += 5 
print type(x), id(x), x 
print x, str(x), type(x) 
print x.objects 

他們工作得很好,但如果i'l取消註釋行x += 5 X成爲<type 'int'>

完全,我希望有階級,有我可以爲整數工作(x = x +-*\ y等),但也可以訪問額外的領域,如果有必要(x.objects) 我認爲我需要覆蓋assignemet方法,但在Python中不可能。任何其他方式對我?

回答

2

對於+=,您可以覆蓋__iadd__

但是,您當前的__add__已損壞。您可以通過使其返回WorldTile(新)實例,而不是一個int修復:

def __add__(self, other): 
    return WorldTile(self.resource + other) 

這兩個++=工作(處理self.objects就留給讀者自己練習)。

+0

有趣的是,我使它看起來像一個int,帶有'+',並且使它看起來像'WorldTile'。 – thefourtheye

+2

這是類的正確方法,它應該模仿不可變內部函數後的行爲。 – wim

+0

@wim謝謝你:)這是有道理的。 – thefourtheye