【发布时间】:2021-05-21 11:38:55
【问题描述】:
我在P1 类中重载了加法运算符,使实例可以直接相加。但是,在执行p1 + p2 时会发生内存错误。 p1.data + p2.data 可以给出正确的结果。
class P1:
def __init__(self):
self.data = np.zeros((512,512),dtype='float64')
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, item):
return self.data[item]
def __add__(self, other):
return self.data + other
def __radd__(self, other):
return other + self.data
p1 = P1()
p2 = P1()
p1 + p2
Traceback (most recent call last):
File "D:\professional\Anaconda_install\lib\site-packages\IPython\core\interactiveshell.py", line 3418, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-224-a0c3d63f397c>", line 1, in <module>
p1 + p2
File "<ipython-input-221-ba43c19b29b0>", line 12, in __add__
return self.data + other
File "<ipython-input-221-ba43c19b29b0>", line 15, in __radd__
return other + self.data
MemoryError: Unable to allocate 2.00 MiB for an array with shape (512, 512) and data type float64
谁能帮我解释一下?
【问题讨论】:
标签: python python-3.x class operator-overloading python-class