开发者

Python: Sharing variables between classes/objects

开发者 https://www.devze.com 2023-04-03 02:49 出处:网络
Ok I have two classes and one is dependent on 开发者_如何学Pythonthe other. So I need to get a variable from the first class and use it in the second.

Ok I have two classes and one is dependent on 开发者_如何学Pythonthe other. So I need to get a variable from the first class and use it in the second. But the second variable is constantly changing. Like this:

class class1 :
    var1 = 0
    def meth1 (self):
        self.var1 += 1
class class2:
    var2 = class1.var1
    def see (self):
        return self.var2
obj1 = class1()
obj2 = class2()

obj1.meth1()
obj2.see()

This would return 0 not 1. If I say print var1 in class one it prints that changed var. But when class2 gets it it is still 0... I guess it is still referring to the old var1. What am I doing wrong and what should I be doing?

Thanks


class class2:
    var2 = class1.var1

This is a COPY of the current value of class1.var1.

"I need to get a variable from the first class and use it in the second"

Use class1.var1 instead of making a copy of the current value in var2.


All information on how variables are coppied is true, and the recommended article is well explained. But if you use class1.var1 you will never get the value og the self.var1 from class1. You can check why with the following code:

class Class1 :
var1 = 0
def meth1 (self):
    self.var1 += 1
    print(id(self.var1))

class Class2:
def meth2 (self):
    print(id(Class1.var1))

obj1 = Class1()
obj2 = Class2()

obj1.meth1()
obj2.meth2()

Where you get different ids for Class1.var1 ( which is var1 in line 2) and self.var1.

If you want to get the value of self.var1 from Class2, you must initialize var1 outside the class, and make it global inside the function where you add it a number:

var1 = 0
class class1 :

    def meth1 (self):
        global var1
        var1 += 1

class class2:

    def meth2 (self):
        print(var1)

obj1 = class1()
obj2 = class2()

obj1.meth1()
obj2.meth2()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号