Python对象组合 - 从调用它的类访问方法

时间:2012-03-22 12:48:23

标签: python oop composition

你必须原谅我,我正在努力教自己OO,但我遇到了这个问题,包括作文和'有一个'的关系。

class Main(object):
    def A(self):
        print 'Hello'
    def B(self):
        self.feature = DoSomething()

class DoSomething(object):
    def ModifyMain(self):
        #Not sure what goes here... something like
        Main.A()

def run():
    M = Main()
    M.B()

上述简化的一个真实示例是PySide应用程序,其中Main是MainWindow,而DoSomething是一个动态创建的小部件,放置在窗口的某个位置。我希望DoSomething能够修改主窗口的状态栏,主要是调用(在Main中)self.statusbar()。

如果PySide中有一个快捷方式可以做到这一点,Tops !!请告诉我!但是,我实际上是采用更普遍的Pythonic方法来做到这一点。

我觉得我很接近......我无法让它发挥作用......

2 个答案:

答案 0 :(得分:2)

为什么不使用信号和插槽?这是更多的Qt和OOP方式。

在动态创建的小部件类中:

self.modifyMain = QtCore.Signal(str)

在你的主要课程中:

@QtCore.Slot(str)
def changeStatusbar(self, newmessage):
    statusBar().showMessage(newmessage)
创建窗口小部件后,在主类中

doSomething.modifyMain.connect(self.changeStatusbar)

在你要更改main状态栏的widget类中,你说:

modifyMain.emit("Hello")

这些都没有经过测试,因为我没有方便的PySide安装。

答案 1 :(得分:1)

您的代码存在两个问题:

  1. 你什么时候打电话给ModifyMain;和
  2. Main.A()会导致错误,因为A是一个实例方法,但您在上调用它。
  3. 你想要这样的东西:

    class Main(object):
        def A(self):
            print 'Hello'
        def B(self):
            self.feature = DoSomething() # self.feature is an instance of DoSomething
            self.feature.ModifyMain(self) # pass self to a method
    
    class DoSomething(object):
        def ModifyMain(self, main): # note that self is *this* object; main is the object passed in, which was self in the caller
            #Note case - main, not Main
            main.A()
    
    def run():
        M = Main()
        M.B()
    
    if __name__=="__main__": # this will be true if this script is run from the shell OR pasted into the interpreter
        run()
    

    你的名字都藐视PEP8中常见的python约定,这是python风格的一个很好的指南。我已将它们保留在您的代码中,但不要复制此示例中的样式 - 请遵循PEP8。

相关问题