实例变量的更改未在引用相同变量的元组中更新

Change in instance variable not getting updated in tuple referring the same variable

对于这段代码,当我使用 change()x 更改为 k 然后调用 self.co 它不会 return [= 的更新值15=]。一般如何解决此类问题(这是一个基本示例)?

class scope:
    tag=1
    def __init__(self,h,x):
        self.h = h
        self.x = x
        self.co=(self.x,self.h)
    def change(self,k):
        self.x=k

您没有更改 self.co attribute。您仅在 scope 的初始化发生时分配给 self.co,即当您调用 scope() 时。此外,Python 不会像 c 中的指针那样保留引​​用,因此更改一个不会改变另一个。

为了证明这个 运行 这个代码:

class scope:
    tag=1
    def __init__(self,h,x):
        self.h = h
        self.x = x
        self.co=(self.x,self.h)
    def change(self,k):
        self.x=k

s = scope(2,3)
print(s.co)
print("id of self.x before change:", id(s.x)) #11161896
print("id of self.co's x before change:", id(s.co[0])) #11161896
s.change(6)
print(s.co)
print("id of self.x after change:", id(s.x))  #11161824
print("id of self.co's x after change:", id(s.co[0])) #11161896

id是对象的内存位置,你可以看到它一开始是一样的,但是当你改变self.x时,co中的内存位置没有改变

您必须在 change() 中更新 self.co。如果你想要一个动态变化的co而不需要手动更新它,写一个方法来检索co。

选项 1:

class scope:
    tag=1
    def __init__(self,h,x):
        self.h = h
        self.x = x
        self.co=(self.x,self.h)
    def change(self,k):
        self.x=k 
        self.co = (self.x,self.h)

选项 2:

class scope:
    tag=1
    def __init__(self,h,x):
        self.h = h
        self.x = x
    def change(self,k):
        self.x=k
    def co(self):
        return (self.x,self.h)

s = scope(2,3)
print(s.co()) #(3,2)
s.change(6)
print(s.co()) #(6,2)

您可以使用装饰器 @property 添加到方法 2 以使其不成为函数调用,但此时,我不知道您的要求是什么。

您应该通过使用 @property 装饰器将 self.co 定义为 class 的 property。例如:

class Scope:
    tag=1
    def __init__(self,h,x):
        self.h = h
        self.x = x
    def change(self,k):
        self.x=k
    @property
    def co(self):
        return (self.x, self.h)

样本运行:

>>> s = Scope(3, 5)
>>> s.co   # initial value
(5, 3)
>>> s.change(45)  # update value of `self.x`
>>> s.co   # updated value
(45, 3)

这里,在调用self.co时会return每次调用(self.x, self.y)的动态值。


您的代码有问题:在您的代码中,当您在 __init__ 中初始化 self.co = (self.x,self.h) 时,创建了一个新的元组 self.co持有 (self.x, self.y) 的值(未持有对这些变量的引用)。因此,当您更新 self.x 时,它并没有在您的元组对象中更新。

您必须使用定义的名称调用函数 其次,您也可以使用 global 关键字 例如

value = 10
Update()
def Update():
    global value
    value = 11