2016-06-29 40 views
0

在Functions类中,我想访问Frame类的变量。如何访问其他类中的变量

请告诉我,如果有任何方法。

class Functions(): 

    def changeText(): 
     ... 
     ... 
     I want to change the 'text' in the Frame class 
     ex)Frame.text.SetFont('change text') 

GUI元素

class Frame(wx.Frame):  

    def __init__(self, parent, id, title): 
     wx.Frame.__init__(self, parent, id, title, ....) 
    .... 
    .... 
    self.text = wx.StaticText(panel, .....) 
+1

你有没有尝试让变量全局? –

+0

由于您的缩进而无法确定此属性是'text'对象属性('self.text')还是类属性? – cdarke

回答

0

您可以通过发送一个类的实例的功能做到这一点:

class myClass(object): 
    def __init__(self, text): 
     self.text = text 

def changeText(input): 
    input.text = "world" 

example = myClass("hello") 
changeText(example) 
+0

谢谢你的回答。但你的例子和我的问题似乎有点不同。 我想在课堂外改变GUI类(wx.Frame)中的变量。 –

0

你必须告诉你的对象是什么去努力。凭空告知你的Functions实例不知道(应该怎么做?)Frame应该是什么。你可以让Frame成为全局的,但我认为这不是一个好主意(如果你想使用多个框架实例,它会中断)。所以你会写:

class Functors: 
    ... 
    def set_text(txt_frame, the_text): 
     """txt_frame has to be a :class:`my_txt_frm` instance with ``self.text`` being a ``StaticText`` instance.""" 
     txt_frame.text.SetLabel(the_text) 

class my_txt_frm(wx.Frame): # do not name the derived class Frame to make more clear it is derived! 
    def __init__(# ... 
     ... 
     self.text = wx.StaticText(#... 

所以现在来了有趣的部分:如何将部件连接在一起?你必须有类似的东西在某处代码:

funct = Functors() # the class which know how to do things on our GUI elements 
frm = my_txt_frm(#... 

后来有些线路...

funct.set_text(frm, 'thenewtext') 

因此,对于您的应用程序,它拥有大局观,有必要保持引用到建筑以便能够将它们绑在一起。

将事情联系在一起的有序方法称为MVC(see a great example in the wxPython wiki)。即使你不想在这个范例之后为你的应用程序建模,你也可以从中学习如何推断关注点分离。