54 lines
1.2 KiB
Python
54 lines
1.2 KiB
Python
from error import *
|
|
|
|
|
|
class Memory:
|
|
def __init__(self, size):
|
|
self.data = [0] * size
|
|
self.size = size
|
|
self.name = "内存"
|
|
|
|
def init(self):
|
|
print("重置" + self.name)
|
|
self.data = [0] * self.size
|
|
|
|
def __getitem__(self, key: int):
|
|
print("读取位于", key, "的" + self.name)
|
|
if key > self.size:
|
|
raise AddressError
|
|
return self.data[key]
|
|
|
|
def write(self, index: int, val: int):
|
|
if index > self.size:
|
|
raise AddressError()
|
|
self.data[index] = val
|
|
|
|
def __len__(self):
|
|
return self.size
|
|
|
|
def __str__(self):
|
|
return str(self.data)
|
|
|
|
def __setitem__(self, k, v):
|
|
print("写入位于", k, "的" + self.name)
|
|
|
|
if isinstance(k, slice):
|
|
if not k.start:
|
|
start = 0
|
|
else:
|
|
start = k.start
|
|
if not k.stop:
|
|
stop = self.size - 1
|
|
else:
|
|
stop = k.stop
|
|
|
|
if start > self.size or stop > self.size:
|
|
raise AddressError
|
|
|
|
self.data[start:stop] = v
|
|
return
|
|
|
|
if k > self.size:
|
|
raise AddressError
|
|
self.data[k] = v
|
|
return
|