2012-03-09 58 views
1

我有一個wxPython應用程序,其代碼如下所示。我想設置MyFrame類的屬性值,但我無法引用它。
我該如何使這個代碼工作?親子參考問題python

class MyFrame1(wx.Frame): 
    def __init__(self, *args, **kwds): 
     wx.Frame.__init__(self, *args, **kwds) 
     self.gauge_1 = wx.Gauge(self, -1) 
     self.notebook_1=myNotebook(self, -1) 

class myNotebook(wx.Notebook): 
    def __init__(self, *args, **kwds): 
     wx.Notebook.__init__(self, *args, **kwds) 
     self.other_class_1=other_class() 
     self.other_class_1.do_sth() 

class other_class(object): 
    def do_sth(self): 
     gauge_1.SetValue(value) #doesn't work of course, how do I do this? 
+0

我不覺得你可以在沒有先解釋'other_class'的作用是什麼的情況下得到合適的答案嗎?它真的應該是一個通用的類,它保存對你的MyFrame實例的引用嗎?這裏有什麼用法?就我們所知,MyFrame1可以有一個全局實例,可以通過'other_class'實例直接訪問。 – jdi 2012-03-10 00:06:56

+0

我剛剛意識到'other_class'是什麼後,足夠盯着足夠。奇怪的 – jdi 2012-03-10 00:11:58

回答

1

我認爲它的一個子UI元素設計稍差,有關於其父的具體知識。它是一個倒退式設計。兒童通常應該有某種方式發出信號或舉辦活動,並讓適當的聽衆作出反應。但是,如果這真的是你想要做的,那麼你可能想要獲取父項並直接對其執行操作...

注意:不要這樣做。我正在說明爲什麼設計有問題...

首先,你甚至不能用代碼的結構來完成它,因爲other_class沒有引用父項。它是一個通用實例。所以,你將不得不做這樣的事情......

class other_class(object): 

    def __init__(self, parent): 
     self.parent = parent 

而在你的筆記本電腦類...

class myNotebook(wx.Notebook): 
    def __init__(self, *args, **kwds): 
     wx.Notebook.__init__(self, *args, **kwds) 
     # note here we pass a reference to the myNotebook instance 
     self.other_class_1 = other_class(self) 
     self.other_class_1.do_sth() 

然後,一旦你other_class現在知道它的父,你必須得到的父父級擁有MyFrame1實例...

class other_class(object): 

def __init__(self, parent): 
    self.parent = parent 

def do_sth(self, value): 
    self.parent.GetParent().gauge_1.SetValue(value) 

你現在看到爲什麼它的設計不好嗎?多層次的對象必須假定父結構的知識。

我不是在我的wxPython的,所以我不能給你具體細節,但這裏有一些可能的一般的方法來考慮:

  1. 確定什麼other_class的作用確實是。如果它真的意味着操作MyFrame1的子項,那麼該功能屬於MyFrame1,因此它可以知道這些成員。
  2. 如果other_class是一個wx對象,當調用do_sth()方法時它可能會發出wx.Event。您可以在MyFrame1或Notebook級別綁定該事件,並在處理程序中執行所需的任何工作。
+0

謝謝你的明確和廣泛的答案。我知道我不應該,但最終我使用了'self.parent.GetParent()'方式。我已經有太多的代碼來完全重新設計我的程序。但是,在編寫未來的程序時,我會記住你的提示,然後希望有更好的設計。 – BrtH 2012-03-10 13:04:10

0

嘗試是這樣的:

class other_class(object): 
    def __init__(self): 
     self.g1=MyFrame1() 
    def do_sth(self): 
     self.g1.gauge_1.SetValue(value)