python 如何使用另一个实例的方法更改一个实例的属性
How to change attributes of one instance with a method of another instance in python
我正在尝试通过更改另一个 class 的属性来更改一个 class 实例的属性。但是,在某些情况下,属性不会按预期更改。
假设我有一个 class 点,它包含该点的 x 坐标
class Dot:
def __init__(self, x = 0):
self.x = x
和另一个 class 布料,它使用 Dot 实例列表进行初始化
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
class 布料有一个属性 x,其中 returns 一个包含 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
是否有解决该问题的方法,或者是由于 classes 的糟糕设计?
正如 geckos 上面提到的,这里的问题是在两个地方复制数据的设计决策,而不是让您的 Cloth
对象提供数据接口。通过将数据从 Dot
对象复制到 _x
数组,我们混淆了每个 class 的目的并给我们自己带来了同步问题。
像这样传递到底层数据怎么样?
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
我们两个 class 的工作现在很好地分开了。 Dot
的工作是存储 x
数据,Cloth
的工作是以数组格式为该数据提供接口。
我正在尝试通过更改另一个 class 的属性来更改一个 class 实例的属性。但是,在某些情况下,属性不会按预期更改。
假设我有一个 class 点,它包含该点的 x 坐标
class Dot:
def __init__(self, x = 0):
self.x = x
和另一个 class 布料,它使用 Dot 实例列表进行初始化
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
class 布料有一个属性 x,其中 returns 一个包含 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
是否有解决该问题的方法,或者是由于 classes 的糟糕设计?
正如 geckos 上面提到的,这里的问题是在两个地方复制数据的设计决策,而不是让您的 Cloth
对象提供数据接口。通过将数据从 Dot
对象复制到 _x
数组,我们混淆了每个 class 的目的并给我们自己带来了同步问题。
像这样传递到底层数据怎么样?
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
我们两个 class 的工作现在很好地分开了。 Dot
的工作是存储 x
数据,Cloth
的工作是以数组格式为该数据提供接口。