首页 > 解决方案 > 从另一个类更改实例变量

问题描述

我正在尝试self.var_1从另一个类更改下面的代码,但我收到错误test1 has no attribute 'var_1'。我觉得我犯了一个简单的错误,但似乎找不到问题所在。

class test1:
    def __init__(self):
        self.var_1 = "bob"
        instance2 = test2()

    def change_var(self, new_var):
        print(self.var_1) #should print "bob"
        self.var_1 = new_var #should change "bob" to "john"
        print(self.var_1) #should print "john"

class test2:
    def __init__(self):
        test1.change_var(test1, "john")

instance = test1()

标签: pythonclass

解决方案


var_1是一个实例变量,所以需要使用实例:

class test1:
    def __init__(self):
        self.var_1 = "bob"
        instance2 = test2(self)    # <<<<<< pass test1 instance

    def change_var(self, new_var):
        print(self.var_1) #should print "bob"
        self.var_1 = new_var #should change "bob" to "john"
        print(self.var_1) #should print "john"

class test2:
    def __init__(self, t1obj):      # <<<< take test1 instance
        t1obj.change_var("john")    # <<<< use test1 instance

instance = test1()

给出:

bob
john

推荐阅读