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

前端 未结 6 602
自闭症患者
自闭症患者 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 16:51

    No one has provided a code example showing a way to do this without changing the init arguments. You could simply use a variable in the outer scope that defines the two classes. This won't work if one class is defined in a separate source file from the other however.

    var1 = None
    class foo():
      def __init__(self)
        self.var1 = var1 = 1
    
    class bar():
      def __init__(self):
        print var1
    
    f = foo()
    b = bar()
    

提交回复
热议问题