代码之家  ›  专栏  ›  技术社区  ›  Matt

从另一个类更改实例变量

  •  0
  • Matt  · 技术社区  · 7 年前

    我在努力改变 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()
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   cdarke    7 年前

    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
    
        2
  •  1
  •   Sunny Patel    7 年前

    singleton pattern

    above SO question

    def singleton(class_):
        instances = {}
        def getinstance(*args, **kwargs):
            if class_ not in instances:
                instances[class_] = class_(*args, **kwargs)
            return instances[class_]
        return getinstance
    
    @singleton
    class Test1(object):
        def __init__(self):
            self.var_1 = "bob"
    
        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(object):
        def __init__(self):
            test1 = Test1()
            test1.change_var("john")
    
    Test2()
    

    repl.it