我有一个类叫做细胞:在自定义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