【发布时间】:2011-04-12 20:27:45
【问题描述】:
我有一个名为 Cell 的类:
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能够通过键获得索引?你有没有试过取整数的长度?此外,这可能不应该是社区 wiki:没有人会因为这样回答而得到分数,我们喜欢我们在 SO 的一些分数。 -
-1:这不应该是维基。
-
@AaronMcSmooth
self._value可以保存任何数据类型,所以我希望所有可能的方法都可用。 -
很抱歉设置了这个“社区维基”。我没有意识到残疾点是不可逆转的。现在我知道了。
标签: python class methods overriding