,具體行爲在你的例子中(A*3
給出了A
中數據的三個連接副本),你想實現__mul__()
操作符。
例如,這些是等價的:
>>> a = [1,2,3]
>>> a*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> a.__mul__(3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>>
更一般地,如果你想實現一個序列類型,你必須實現所有operations defined for sequence types的。你必須定義 -
- 什麼
A[3]
手段(__getitem__()
,__setitem__()
)
- 什麼
A[1:10]
手段(__getslice__()
)
- 什麼
for item in A:
手段(__iter__()
)
等。
這裏有list
已定義的方法的完整列表:
>>> pprint.pprint(dict(list.__dict__))
{'__add__': <slot wrapper '__add__' of 'list' objects>,
'__contains__': <slot wrapper '__contains__' of 'list' objects>,
'__delitem__': <slot wrapper '__delitem__' of 'list' objects>,
'__delslice__': <slot wrapper '__delslice__' of 'list' objects>,
'__doc__': "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items",
'__eq__': <slot wrapper '__eq__' of 'list' objects>,
'__ge__': <slot wrapper '__ge__' of 'list' objects>,
'__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>,
'__getitem__': <method '__getitem__' of 'list' objects>,
'__getslice__': <slot wrapper '__getslice__' of 'list' objects>,
'__gt__': <slot wrapper '__gt__' of 'list' objects>,
'__hash__': None,
'__iadd__': <slot wrapper '__iadd__' of 'list' objects>,
'__imul__': <slot wrapper '__imul__' of 'list' objects>,
'__init__': <slot wrapper '__init__' of 'list' objects>,
'__iter__': <slot wrapper '__iter__' of 'list' objects>,
'__le__': <slot wrapper '__le__' of 'list' objects>,
'__len__': <slot wrapper '__len__' of 'list' objects>,
'__lt__': <slot wrapper '__lt__' of 'list' objects>,
'__mul__': <slot wrapper '__mul__' of 'list' objects>,
'__ne__': <slot wrapper '__ne__' of 'list' objects>,
'__new__': <built-in method __new__ of type object at 0x1E1DACA8>,
'__repr__': <slot wrapper '__repr__' of 'list' objects>,
'__reversed__': <method '__reversed__' of 'list' objects>,
'__rmul__': <slot wrapper '__rmul__' of 'list' objects>,
'__setitem__': <slot wrapper '__setitem__' of 'list' objects>,
'__setslice__': <slot wrapper '__setslice__' of 'list' objects>,
'__sizeof__': <method '__sizeof__' of 'list' objects>,
'append': <method 'append' of 'list' objects>,
'count': <method 'count' of 'list' objects>,
'extend': <method 'extend' of 'list' objects>,
'index': <method 'index' of 'list' objects>,
'insert': <method 'insert' of 'list' objects>,
'pop': <method 'pop' of 'list' objects>,
'remove': <method 'remove' of 'list' objects>,
'reverse': <method 'reverse' of 'list' objects>,
'sort': <method 'sort' of 'list' objects>}
當您調用'__str__'創建並返回一個NEW字符串對象時,該類不會作爲字符串。我真的不知道你在做什麼... –
子類'元組'。 –