Use class variable in another class

假如想象 提交于 2019-12-13 15:31:50

问题


Greetings everyone,

I'm currently working on an app using Python and wxPython. In it I have a Dialog where several fields are filled in order to insert a "document" in a database. The layout of that Dialog consists basically of a wx.Notebook, with several "tabs", each containing some sort of fields.

# Dialog class
class NovoRegisto(wx.Dialog):
    def __init__(self,parent):
        wx.Dialog.__init__(self, parent, title='Registar Nova O.T.', size=(900,600))

        painel = wx.ScrolledWindow(self, -1, style=wx.VSCROLL|wx.HSCROLL)
        painel.SetScrollbars(0,30,0,500)
        notebook = wx.Notebook(painel)

        # create the page windows as children of the notebook
        pag1 = InfoOT(notebook)
        pag2 = Avaliacao(notebook)
        pag3 = Componentes(notebook)
        pag4 = Material(notebook)
        pag5 = OTsRelacionadas(notebook)

                          <...>
        # function to insert data in SQLite database
        def OnRegister(self,event):
                          <...>

# first tab class
class InfoOT(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

                          <...>

As you can see, I have a class for the Dialog itself (with a definition controlled by a "Register" button) and then a different class for each of the "tabs" of the notebook.

Now, in order to submit the data to the database, I must have access to the "tabs" variables in the "OnRegister" definition (which belongs to the Dialog's class). However, I still haven't found a way to do that.

Can anyone help me? Do I have to change my program's structure? I did it this way because it was the only way I managed to make the notebook work...

Thank you in advance


回答1:


Your "tabs" aren't class variables, they are local variables inside the function __init__. Also you don't want class variables, you want instance variables. To read and write instance variables you need to access them as attributes of self, for example self1.pag1, not by writing their name.

You need to distinguish between:

  • function local variables - variables that you assign within a function
  • class variables - class attributes that you access through the attribute operator (such as NovoRegisto.variable_name)
  • instance variables - instance attributes that you access by using the attribute operator on self (such as self.pag1).

You should probably read more about how Python classes should be used.

As an additional note, you'd most often want to use

super(InfoOT, self).__init__(parent)

over

wx.Panel.__init__(self, parent)

which is available in new-style classes (i.e. all classes that indirectly or directly inherit from the builtin object)



来源:https://stackoverflow.com/questions/4845834/use-class-variable-in-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!