Python: How do I pass variables between class instances or get the caller?

前端 未结 6 607
自闭症患者
自闭症患者 2020-12-05 16:12
class foo():
  def __init__(self)
    self.var1 = 1

class bar():
  def __init__(self):
    print \"foo var1\"

f = foo()
b = bar()

In foo, I am do

6条回答
  •  暖寄归人
    2020-12-05 17:02

    Perhaps this was added to the language since this question was asked...

    The global keyword will help.

    x = 5
    
    class Foo():
        def foo_func(self):
            global x    # try commenting this out.  that would mean foo_func()
                        # is creating its own x variable and assigning it a
                        # value of 3 instead of changing the value of global x
            x = 3
    
    class Bar():
        def bar_func(self):
            print(x)
    
    def run():
        bar = Bar()     # create instance of Bar and call its
        bar.bar_func()  # function that will print the current value of x
    
        foo = Foo()     # init Foo class and call its function
        foo.foo_func()  # which will add 3 to the global x variable
    
        bar.bar_func()  # call Bar's function again confirming the global
                        # x variable was changed 
    
    
    if __name__ == '__main__':
        run()
    

提交回复
热议问题