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

时间:2015-03-06 15:39:36

标签: python object methods main

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

我对OOP不太熟练,所以也许我的理解是错的?有没有更好的方法来实现这一目标?

下面是伪代码;在PyQt中,总体目标是能够从任意其他类的对象的方法内部调用主窗口对象的方法。

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的回复。在查看了这个以及更多的反复试验之后,我想到了一个调用祖先对象方法的例子(即使这些类没有继承关系):

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()

但是我还是比较新手,所以,让我知道是否有更好的方法,或者,如果有什么理由说明为什么整个概念都不必要或者这样。< / p>

1 个答案:

答案 0 :(得分:1)

我已经为您当前的代码做了一些注释。但是,对你的问题的简单回答是你不能在不传递该类的实例的情况下引用另一个类:

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