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中不可能。任何其他方式對我?
有趣的是,我使它看起來像一個int,帶有'+',並且使它看起來像'WorldTile'。 – thefourtheye
這是類的正確方法,它應該模仿不可變內部函數後的行爲。 – wim
@wim謝謝你:)這是有道理的。 – thefourtheye