簡體   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