【发布时间】:2021-12-17 16:40:45
【问题描述】:
让我们考虑以下示例:
point.py
import numpy as np
class Point:
def __init__(self):
self._x = np.array([])
self._y = np.array([])
@property
def x(self) -> np.ndarray:
return self._x
@x.setter
def x(self, value: Union[float, list, np.ndarray]):
self._x = np.atleast_1d(value)
@property
def y(self) -> np.ndarray:
return self._y
@y.setter
def y(self, value: Union[float, list, np.ndarray]):
self._y = np.atleast_1d(value)
现在,如果我执行以下操作:
from point import Point
coordinates = Point()
coordinates.x = [0, 5]
coordinates.x[0] = 3
当我分配列表时,x.setter 会被调用,但在我修改数组元素时不会调用。
如何更新我的代码以触发两者中的设置器?
非常感谢!
【问题讨论】:
-
你真的需要那个:
coordinates.x[0] = 3真的更新coordinates._x吗?使用coordinates.x[0] = ...,您不会触发__set__,只有描述符的__get__,因为[0]指的是“x 的方法”。 -
显示每个作业的结果,并说出问题所在。
标签: python python-3.x numpy properties