Предполагается, что z передается в виде списка (в соответствующем коде Python). z += 3
можно перевести на del z[:3]
, что переводит элемент 3 в 0.
Однако в python вам нужно скопировать массив, прежде чем делать это, потому что с помощью оператора del массив модифицируется.
В C вы можете получить доступ к элементам перед указанным индексом через отрицательные индексы. Это можно сделать с помощью «невидимого» смещения, вложенного в класс. Это смещение всегда добавляется в индекс при доступе к списку.
Следующий класс демонстрирует поведение.
class pointer_like:
def __init__(self, lst):
self.lst = lst; self.offset = 0
# self[index]
def __getitem__(self, index):
return self.lst[self.offset + index]
# self += offset
def __iadd__(self, offset):
self.offset += offset
# other member functions...
# as your example above
def somename(z):
z = pointer_like(z)
while (....):
a += z[0]
b += z[1]
c += z[2]
z += 3
>>> # other example
>>> z = pointer_like([0, 1, 2, 3, 4, 5])
>>> z[0]
0
>>> z += 3
>>> z[0]
3
>>>
>>> # with normal python lists, this would mean third last element
>>> z[-3]
0
>>> z += -5
>>> z[2]
0
>>>
>>> # this is special, because z.offset is negative (-2),
>>> # when a list item is accessed through a negative index,
>>> # it is counted from the end of the array in python.
>>> # In this case, it is -2, so the second last is accessed
>>> # In C this would cause undefined behavor, on most
>>> # platforms this causes an access violation
>>> z[0]
4
Обратите внимание, что pyhon также имеет оператор +=
для списков, но это позволяет добавить еще один список в конце.