繁体   English   中英

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

[英]How to change attributes of one instance with a method of another instance in python

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

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

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

和另一个用Cloth类实例初始化的类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坐标的列表,以及一个getter和setter方法,该方法允许更改x的列表。 如果我现在更改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

有没有解决这个问题的方法,或者是由于类的设计不当?

正如上面的壁虎所提到的,这里的问题是在两个位置复制数据的设计决策,而不是让Cloth对象提供数据的接口。 通过将数据从Dot对象复制到_x数组,我们会混淆每个类的用途,并给自己带来一个同步问题。

像这样直接传递给底层数据怎么样?

class Cloth:
    def __init__(self, dots):
        self.dots = dots

    @property
    def x(self):
        return (dot.x for dot in self.dots)

    @x.setter
    def x(self, arr):
        for value, dot in zip(arr, self.dots):
            dot.x = value

现在,我们两个班级的工作已经很好地分开了。 Dot的工作是存储x数据,而Cloth的工作是以数组格式提供该数据的接口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM