在Python中,如何根据作为参数传递的另一个对象的属性来更新属性?

问题描述 投票:0回答:2

好吧,让我们从代码开始,因为它非常明确:

class c_1:
    def __init__(self):
        self.a = 5

class c_2:
    def __init__(self,other_obj):
        self.other = other_obj
        self.b = self.other.a

输出:

obj_1 = c_1()
obj_2 = c_2(obj_1)
print(obj_2.b)
# Output is 5
obj_1.a = 8
print(obj_2.b)
# Output is still 5

这就是问题所在。我知道 obj_2.b 的第二次调用应该返回 5,但我希望它返回 8。

我认为我真正想要的是通过 obj_2.b 的引用传递 obj_1.a 的值(这个示例非常简单,但在我的实际代码中,obj_2 使用了 obj_1 中的更多属性。)

有没有一种方法,可以在不调用其他方法的情况下,在 obj_1.a 的值发生更改时自动更新 obj_2.b ?谢谢你。

python python-3.x oop object attributes
2个回答
2
投票

这是可能的,但您的里程可能会有所不同,具体取决于您的用例:

如下所示,一种方法是实现一个

Var class
来为您处理此问题;将值封装在对象内可以规避“通过值”,并打开“”的可变性。这是一个不完整(且脆弱)的示例;有很多极端情况需要解决以使其顺利工作,但回答你的问题:是的,这绝对是可能的:

其他方法可能会使用

inspect module
metaclasses
或实现
callbacks

python 标准库中的

tkinter
使用专门的类和回调方法。

class Var:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value

    def __repr__(self):
        return str(self._value)


class IntVar(Var):

    def __iadd__(self, other: int):
        self._value = self._value + other
        return self.value


class c_1:
    def __init__(self):
        self._a = IntVar(5)

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a.value = value


class c_2:
    def __init__(self, other_obj):
        self.other = other_obj
        self.b = self.other.a


obj_1 = c_1()
obj_2 = c_2(obj_1)
print(obj_2.b)
obj_1.a = 8
print(obj_2.b)
obj_1.a += 2
print(obj_2.b)

输出:

5
8
10

2
投票

有没有一种方法,无需调用其他方法,就可以自动 当 obj_1.a 的值更改时更新 obj_2.b 吗?谢谢你

答案是否定的。

c_2
的构造函数将
b
的值设置为
other_obj.a
,然后固定
b
的值,直到您再次显式更改其值。将其视为普通(标量)变量 - 一旦设置了值,它就不会更改,直到您显式为其分配新值。

如果要在

a
中引用
c_2
的值,则应始终引用
self.other.a
,因为
self.other
是对传递给构造函数的
other_obj
的引用。

© www.soinside.com 2019 - 2024. All rights reserved.