簡體   English   中英

Python對象組合 - 從調用它的類訪問方法

[英]Python object composition - accessing a method from the class that called it

你必須原諒我,我正在努力教自己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方法來做到這一點。

我想我很接近......我無法讓它發揮作用......

為什么不使用信號和插槽呢? 這是更多的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. 你什么時候打電話給ModifyMain ;
  2. Main.A()將導致錯誤,因為A是實例方法,但您在上調用它。

你想要的東西:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM