1

Is there a more pythonic way of 'linking' attributes such that when one attribute in a class is changed, another can be automatically changed according to some relation that I define?

Currently, I'm doing something like:

class myClass(object):
    def __init__(self):
        self.x = 1
        self.y = 2 * self.x
        pass
    def set_x(self, x):
        self.x = x
        self.y = 2 * self.x
        return
A = myClass()
print A.x #prints 1
print A.y #prints 2
A.set_x(5)
print A.x #prints 5
print A.y #automatically changes to 10
4

2 回答 2

4

您可以使用属性:

class myClass(object):
    def __init__(self):
        self.x = 1

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

    @x.setter
    def x(self, x):
        self._x = x
        self.y = 2 * self._x

和一个测试:

>>> c= myClass()
>>> c.x = 10
>>> c.x
10
>>> c.y
20
于 2012-08-14T01:16:58.617 回答
3

您可以使用 getter 和 setter:

class myClass(object):
    def __init__(self):
        self.x = 1

    @property
    def y(self):
        return 2 * self.x
    ...

基本上,这就是说当您尝试获取 Ay 时,它会返回 self.x * 2 。

考虑到班上的其他人,我实际上会做这样的事情:

class myClass(object):
    def __init__(self):
        self._x = 1

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

    @property
    def y(self):
        return 2 * self._x

    @x.setter
    def x(self, val):
        self._x = val
于 2012-08-14T01:17:40.503 回答