我有一个 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 更新时更新。
如果这让您感到困惑,我深表歉意。非常感谢您帮助这个新手。
-杰森
最佳答案
您可以将x
和y
定义为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
这样,x
和 y
就不是属性(因此数据只在 datum
中存储一次),但仍然可用因此(即:my_shape.x
和 my_shape.y
按预期工作)。
关于python - 更改另一个属性时分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16353867/