如何访问其他类中的变量

2024-04-16 04:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在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, .....)

Tags: thetextselfidtitleinitdeffunctions
2条回答

你必须告诉你的对象要做什么。凭空你的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)。即使您不想按照这种模式来建模应用程序,您也可以从中学习如何对关注点分离进行推理。你知道吗

您可以通过向函数发送类的实例来执行此操作:

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

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

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

相关问题 更多 >