如何使用python中另一个实例的方法更改一个实例的属性

问题描述 投票:2回答:1

我试图通过更改另一个类的属性来更改一个类的实例的属性。但是,在某些情况下,属性不会按预期更改。

假设我有一个类Dot,它保存该点的x坐标

class Dot:
    def __init__(self, x = 0):
        self.x = x

和另一个用一个Dot实例列表初始化的Cloth

class Cloth:
    def __init__(self, dots):
        self.dots = dots
        self._x = [dot.x for dot in dots]

    @property 
    def x(self):
        return self._x

    @x.setter
    def x(self, arr):
        for ii in range(len(arr)):
            self.dots[ii].x = arr[ii]   
        self._x = arr

Cloth类有一个属性x,它返回一个包含Dot实例的所有x坐标的列表,以及一个允许更改x列表的getter和setter方法。如果我现在更改x坐标列表,它可以很好地工作

#instantiate list of dots
dots = [Dot(x = 1), Dot(x = 2), Dot(x = 3)]
#instantiate the cloth
cloth = Cloth(dots)

#change all x-coordinates at once
cloth.x = [2, 3, 4]

print(cloth.x) 
#returns [2, 3, 4]
print(cloth.dots[0].x) 
#returns 2

但是,如果我只尝试更改一个x坐标,则不会更改该点实例的x坐标,因为未调用setter方法

#change one x-coordinate
cloth.x[0] = -1

print(cloth.x) 
#returns [-1, 3, 4]
print(cloth.dots[0].x) 
#still returns 2 instead of -1

有没有解决这个问题的方法,还是因为类的设计不好?

python oop getter-setter
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.