Python 类 : linked attributes

标签 python class attributes

是否有一种更 pythonic 的“链接”属性的方法,这样当类中的一个属性发生变化时,另一个可以根据我定义的某种关系自动更改?

目前,我正在做类似的事情:

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

最佳答案

您可以使用属性:

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

关于Python 类 : linked attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11944436/

相关文章:

html5 : Significance of attribute named required in checkbox/radio

python - Firebird 在特定目录中创建数据库

python - 在 python 中的列表中附加列表中的项目时出现问题

python - 在 Numpy 中导出 ISO 日期

class - Dart flutter : The default value of an optional parameter must be constant when setting a default value to class constructor

python - 属性错误 : 'Doctype' object has no attribute 'has_attr'

Python 迭代器 : What does iglob( )'s Iterator provide over glob()' s list?

python - 为什么属性在 Python 中跨类继承?

java - 将类作为 java 中方法的参数传递

c# - 如何将属性应用于继承树中的单个类型?