我有一個類叫做細胞:在自定義Python類中覆蓋默認方法的簡單方法?
class Cell:
def __init__(self, value, color, size):
self._value = value
self._color = color
self._size = size
# and other methods...
Cell._value
將存儲一個字符串,整數,等等。(不管我使用的對象)。我想,通常會用「價值」的對象來使用<Cell object>._value
所有默認的方法,這樣我可以做的:
>>> c1 = Cell(7, "blue", (5,10))
>>> c2 = Cell(8, "red", (10, 12))
>>> print c1 + c2
15
>>> c3 = Cell(["ab", "cd"], "yellow", (50, 50))
>>> print len(c3), c3
2 ['ab', 'cd']
# etc.
我可以覆蓋所有的默認方法:
class Cell:
def __init__(self, value, color, size):
# ...
def __repr__(self):
return repr(self._value)
def __str__(self):
return str(self._value)
def __getitem__(self, key):
return self._value[key]
def __len__(self):
return len(self._value)
# etc.
...但有沒有更簡單的方法?
爲什麼一個整數'self._value'有能力被一個鍵索引?你有沒有嘗試過一個整數的長度?另外,這可能不應該是cocmmunity wiki:沒有人會以這種方式回答問題,我們在這裏愛我們的一些觀點。 – aaronasterling 2010-09-15 18:48:58
-1:這不應該是一個維基。 – 2010-09-15 18:49:18
@AaronMcSmooth'self._value'可以容納任何數據類型,所以我想擁有所有可能的方法。 – 2010-09-16 12:41:40