关联/链接多个属性的简洁方法,即当其中任何一个更改时自动更新其他属性?

时间:2018-12-12 10:47:47

标签: python

例如,如果一个类具有三个属性,/* define SearchResultResponseForlocation as an array... i have used any but you should define a class for your object as per cities.json*/ SearchResultResponseForlocation:any[]; searchResultMethodForLocation(fl: string){ this.http.get('/assets/js/cities.json' + term).pipe( ).subscribe( data => { this.SearchResultResponseForlocation = JSON.parse(data); console.log(this.SearchResultResponseForlocation[0].name); this.searchFindLoopForLocation = this.SearchResultResponseForlocation; }, error => { console.log("Error in recieving data"); }, () => { console.log(this.SearchResultResponse); } ); } (整数),x(整数)和y(2元素列表)。

他们满足:xyx=xy[0]。 (y=xy[1]在数学上代表“ euqal”。)

=x更改时,自动更新y,而当xy更改时,自动更新xyx

我已经使用y@property以非常丑陋的方式实现了这一点。

@setter

(一些if-else句子用于检查初始值的存在,避免无限次递归分配相同的值。)

我认为必须存在更干净,更通用的方法来实现相同的目标。说,有没有像这样的简单语法:

class AAA:

    ...

    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, val):
        if '_x' in self.__dict__:
            if self.x == val:
                return
        self._x = val
        if not '_y' in self.__dict__:
            self.xy = [val, 0]
        else:
            self.xy = [val, self.y]

    @property
    def y(self):
        return self._y
    @y.setter
    def y(self, val):
        if '_y' in self.__dict__:
            if self.y == val:
                return
        self._y = val
        if not '_x' in self.__dict__:
            self.xy = [0, val]
        else:
            self.xy = [self.x, val]

    @property
    def xy(self):
        return self._xy
    @xy.setter
    def xy(self, val):
        if '_xy' in self.__dict__:
            if self.xy == val:
                return
        self._xy = val
        self.x = val[0]
        self.y = val[1]

1 个答案:

答案 0 :(得分:1)

使用具有默认值的视图:

class AAA:
    def __init__(self):
        self._value = [0, 0]  # or perhaps [None, None]

    @property
    def x(self):
        return self._value[0]
    @x.setter
    def x(self, val):
        self._value[0] = val

    @property
    def y(self):
        return self._value[1]
    @y.setter
    def x(self, val):
        self._value[1] = val

    @property
    def xy(self):
        return self._value
    @xy.setter
    def xy(self, val):
        # Assert that val is a list/tuple of two elements?
        self._value = val

与您所做的几乎一样,我只是消除了不必要的噪音(所有这些噪音)。

在Python3.x下,您可以使用以下方法进一步简化此操作:

def array_accessor(idx, getter):
    @property
    def prop(self):
        return getter(self)[idx]
    @prop.setter
    def prop(self, val):
        getter(self)[idx] = val
    return prop

def xy_accessor(idx):
    return array_accessor(idx, lambda self: self.xy)

class AAA:
    def __init__(self):
        self.xy = [0, 0]
    x = xy_accessor(0)
    y = xy_accessor(1)