当我更改Python中的实例属性时,如何更新类属性?

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

我正在尝试优化问题。就像您现在一样,优化是一个迭代过程。选择一些部分并计算所有部分的权重。 我写了类似的代码。

class Test:
    W = 0

    def __init__(self, l, A):
        self.l = l
        self.A = A
        Test.W += self.A * self.l


instance1 = Test(5, 10)
instance2 = Test(3, 7)
instance3 = Test(6, 13)

print(Test.W)

instance1.A = 20
instance2.A = 30
instance3.A = 40

print(Test.W)

在第一次采样时,例如1、2、3,程序计算出W的值为149。这对我来说没问题。 但我改变了所有实例的“A”值(或者可以是一两次改变),结果一次又一次地是149。 当我更改“A”或“l”时,如何更新类属性W? 预先感谢

python class instance-variables class-attributes renewal
1个回答
0
投票

在您当前的实现中,属性

W
是所有类实例之间共享的类属性。修改单个实例的属性
A
l
不会影响计算的
W
,因为
W
在实例实例化期间仅计算一次。

如果您想在每次更改实例的

W
W
时重新计算
A
,您可以将
l
设为实例变量。

以下是修改课程的方法:

class Test:
    def __init__(self, l, A):
        self.l = l
        self.A = A
        self.W = self.A * self.l

instance1 = Test(5, 10)
instance2 = Test(3, 7)
instance3 = Test(6, 13)

print(instance1.W + instance2.W + instance3.W)

# Change A for instances
instance1.A = 20
instance2.A = 30
instance3.A = 40

# Recalculate W for each instance
instance1.W = instance1.A * instance1.l
instance2.W = instance2.A * instance2.l
instance3.W = instance3.A * instance3.l

print(instance1.W + instance2.W + instance3.W)

在此修改中,

W
是实例化期间计算的实例变量,当您更改
A
l
时,需要针对特定实例更新
W

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