2012-03-09 57 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)