python - 更改另一个属性时分配属性

标签 python

我有一个 Python Shape 类,它有一个名为 datum 的属性。它是一个包含两个数字 x 和 y 的列表。

如果我这样做

my_shape = Shape()

然后数据被赋予默认值:[0,0] 现在,我想通过以下方式重新分配数据:

my_shape.datum = [3,2] 

然后我的数据现在被分配到那个列表。

但我也有属性 x 和 y。如何让x和y自动更新成为数据列表的第一项和第二项?

我把它放在init

self.x = self.datum[0]
self.y = self.datum[1]

但这只会将 x 和 y 分配给初始化值,我不知道如何在 self.datum 更新时更新。

如果这让您感到困惑,我深表歉意。非常感谢您帮助这个新手。

-杰森

最佳答案

您可以将xy 定义为properties :

@property
def x(self):
    return self.datum[0]

@x.setter
def x(self, value):
    self.datum[0] = value

@property
def y(self):
    return self.datum[1]

@y.setter
def y(self, value):
    self.datum[1] = value

这样,xy 就不是属性(因此数据只在 datum 中存储一次),但仍然可用因此(即:my_shape.xmy_shape.y 按预期工作)。

关于python - 更改另一个属性时分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16353867/

相关文章:

python - 是否可以从 Dataframe 的 View 中排除索引列?

python - 字典键作为类中的函数

python - scipy convolve2d 输出错误的值

python - 使用 python 将 DataFrame 列日期从 2/3/2007 格式转换为 20070223

python - 返回 iter 中 lambda 的产量

python - 更有效/干净的方式来聚合数据

Python:如何重置 turtle graphics 窗口

python - 使用填充堆叠不同长度的 Numpy 数组

python - 为什么在 oracledb/cx_Oracle (Python) 中不调用输出转换器进行字节转换?

python - 将元组列表转换为列表?