python - main中定义对象的引用方法

python - reference method of object defined in main

在 python 3.4.2 中有没有办法从任何 class 中调用在 main() 中定义的对象的方法?

我对OOP不是很熟练所以可能我的理解有误?有没有更好的方法来实现这个目标?

以下为伪代码;在 PyQt 中,总体目标是能够从任意其他 class.

对象的方法内部调用主要 window 对象的方法
class A(object):
  myVar=0
  def __init__(self):
    pass
  def doit():
    print(self.myVar)

class B(object):
  def __init__(self):
    A.doit()  # uses the class variable, should print '0'
    a1.doit() # uses the object variable, should print '1'

def main():
  a1=A()
  a1.myVar=1
  b1=B()

更新: 感谢 KronoS 的回复。在查看了那个和更多的试验和错误之后,这是我想出的一个调用祖先对象方法的例子(即使 classes 没有继承关系):

class A(object):
    def __init__(self):
        b1=B(self)
    def do_stuff(self):
        print("Stuff is done")

class B(object):
    def __init__(self,parent):
        self.parent=parent # needed so children of this object can reference this object's parent
        c1=C(self)

class C(object):
    def __init__(self,parent):
        parent.parent.do_stuff()
        # or actually make parent an object of this instance;
        #  necessary if children of this object will reference this object's parent:
        #self.parent=parent
        #self.parent.parent.do_stuff()

def main():
    a1=A()

if __name__ == '__main__':
    main()

不过,我对此还是很陌生,所以,请告诉我是否有更好的方法,或者,如果有某种原因为什么整个概念应该是不必要的等等。

我已经对您当前的代码做了一些注释。但是,对您的问题的简单回答是,您不能在不传递 class:

的实例的情况下引用另一个 class
class A(object):
    myVar=0
    def __init__(self):
        pass
    def doit(self):  # <--- Missing 'self' here
        print("A.doit(): {}".format(self.myVar))

class B(object):
    def __init__(self, other):

        #A.doit()       # This will not work.  It's not a class function now that we've added 'self'
        print("B.__init__: {}".format(A.myVar))
        other.doit()    # other is the passed in object


def main():
    a1=A()
    a1.myVar=1
    b1=B(a1)
    print("main: {}".format(A.myVar))



if __name__ == "__main__":
    main()

# Out
# B.__init__: 0
# A.doit(): 1
# main: 0