Python Forum
what does self.classname() do and how is it done?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what does self.classname() do and how is it done?
#1
I'm new to python and I want to know how this syntax is done

>>> self.makeMenuBar() <<< I understand that self is used to bind variables but how can you
use self with a class like it's done in the ff?

here is code sample I'm studying

 def __init__(self, *args, **kw):
        # ensure the parent's __init__ is called
        super(HelloFrame, self).__init__(*args, **kw)

        # create a panel in the frame
        pnl = wx.Panel(self)

        # put some text with a larger bold font on it
        st = wx.StaticText(pnl, label="Hello World!")
        font = st.GetFont()
        font.PointSize += 10
        font = font.Bold()
        st.SetFont(font)



        # and create a sizer to manage the layout of child widgets
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(st, wx.SizerFlags().Border(wx.TOP|wx.LEFT, 25))
        pnl.SetSizer(sizer)

        # create a menu bar
        self.makeMenuBar()

        # and a status bar
        self.CreateStatusBar()
        self.SetStatusText("Welcome to wxPython!")
Reply
#2
that's just the __init__ function of the class (i.e. it is called at the time object of the class is instanciated). The class has other attributes (methods and properties). Obviously it has makeMenuBar() method (along many others, e.g. CreateStatusBar(), SetStatusText(). self.makeMenu() calls this method within body of the __init__(). Note that these methods may be inherited from the parent class.
Can you provide the full code you have?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
@programmy when dealing with a class self is an internal handle to the class -- in other languages you will find this being used for the handle to the self. Now in PyQt the QMainWindow is the only object that comes with a predefined MenuBar and StatusBar but one can create a window with a simple QWidget and unless one needs the MenuBar and/or StatusBar or the Docking region there is no need to use the QMainWindow with all its extra baggage and I am pretty sure this goes for wxPython as well -- here is a PyQt example with some universal comments to maybe help you along in the right direction
# Okay I am assuming PyQt since you did not denote otherwise
class Form(QMainWindow):
    def __init__(self):
# Do not use super unless you fully understand what the pitfalls are
# because frankly the benefits are more rare than the pitfalls are and
# the whole basis for using it is based on lazy coding practices rather
# than anything of quality
       # ensure the parent's __init__ is called
       QMainWindow.__init__(self)
 
# Without the "self." handle this Panel will get  collected by the
# garbage collector and become no more also due to this being a snippet
# there is no definition for this "wx" prefix for even in PyQt you have
# have to import the libraries and I am assuming you did the same with
# wxPython
       # create a panel in the frame
       self.pnl = wx.Panel(self)
 
       # put some text on the panel
       st = wx.StaticText(self.pnl, label="Hello World!")

       # change the text to have a larger bold font
       font = st.GetFont()
       font.PointSize += 10
       font = font.Bold()
       st.SetFont(font)
 
       # create a sizer to manage the layout of child widgets
       sizer = wx.BoxSizer(wx.VERTICAL)
       sizer.Add(st, wx.SizerFlags().Border(wx.TOP|wx.LEFT, 25))
       self.pnl.SetSizer(sizer)
 
       # create a menu bar
# this is a meaningless menubar because you have nothing in it
       self.makeMenuBar()
 
       # and a status bar
       self.CreateStatusBar()
# okay so this wx prefix has something to do with the library you are using 
# that I am guessing you have imported incorrectly because you imported the
# entire library rather than just the elements you are using from that library
       self.SetStatusText("Welcome to wxPython!")
Reply
#4
@Denni, it's clear that OP is using wxPython GUI framework. Adding PyQt example can only confuse them and IMHO is not helpful
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
@buran well I do not know much about wxPython but the comments I made are pretty much universal to all python based GUI code and while different wxPython is at least similar to PyQt in its implementation granted not exactly the same but close enough for the comments to still be valid -- but I have adjusted my lead in comments accordingly
Reply
#6
here's the full code.. yes its wxpython
Smile
import wx

class HelloFrame(wx.Frame):
    """
    A Frame that says Hello World
    """

    def __init__(self, *args, **kw):
        # ensure the parent's __init__ is called
        super(HelloFrame, self).__init__(*args, **kw)

        # create a panel in the frame
        pnl = wx.Panel(self)

        # put some text with a larger bold font on it
        st = wx.StaticText(pnl, label="Hello World!")
        font = st.GetFont()
        font.PointSize += 10
        font = font.Bold()
        st.SetFont(font)



        # and create a sizer to manage the layout of child widgets
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(st, wx.SizerFlags().Border(wx.TOP|wx.LEFT, 25))
        pnl.SetSizer(sizer)

        # create a menu bar
        self.makeMenuBar()

        # and a status bar
        self.CreateStatusBar()
        self.SetStatusText("Welcome to wxPython!")



    def makeMenuBar(self):
        """
        A menu bar is composed of menus, which are composed of menu items.
        This method builds a set of menus and binds handlers to be called
        when the menu item is selected.
        """

        # Make a file menu with Hello and Exit items
        fileMenu = wx.Menu()
        # The "\t..." syntax defines an accelerator key that also triggers
        # the same event
        helloItem = fileMenu.Append(-1, "&Hello...\tCtrl-H",
                "Help string shown in status bar for this menu item")
        fileMenu.AppendSeparator()
        # When using a stock ID we don't need to specify the menu item's
        # label
        exitItem = fileMenu.Append(wx.ID_EXIT)

        # Now a help menu for the about item
        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(wx.ID_ABOUT)

        # Make the menu bar and add the two menus to it. The '&' defines
        # that the next letter is the "mnemonic" for the menu item. On the
        # platforms that support it those letters are underlined and can be
        # triggered from the keyboard.
        menuBar = wx.MenuBar()
        menuBar.Append(fileMenu, "&File")
        menuBar.Append(helpMenu, "&Help")

        # Give the menu bar to the frame
        self.SetMenuBar(menuBar)

        # Finally, associate a handler function with the EVT_MENU event for
        # each of the menu items. That means that when that menu item is
        # activated then the associated handler function will be called.
        self.Bind(wx.EVT_MENU, self.OnHello, helloItem)
        self.Bind(wx.EVT_MENU, self.OnExit,  exitItem)
        self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)


    def OnExit(self, event):
        """Close the frame, terminating the application."""
        self.Close(True)


    def OnHello(self, event):
        """Say hello to the user."""
        wx.MessageBox("Hello again from wxPython")


    def OnAbout(self, event):
        """Display an About Dialog"""
        wx.MessageBox("This is a wxPython Hello World sample",
                      "About Hello World 2",
                      wx.OK|wx.ICON_INFORMATION)


if __name__ == '__main__':
    # When this module is run (not imported) then create the app, the
    # frame, show it, and start the event loop.
    app = wx.App()
    frm = HelloFrame(None, title='Hello World 2')
    frm.Show()
    app.MainLoop(
Reply
#7
The method is created here
import wx
 
class HelloFrame(wx.Frame):
    """
    A Frame that says Hello World
    """
    ...
    ...
    def makeMenuBar(self):
        """
        A menu bar is composed of menus, which are composed of menu items.
        This method builds a set of menus and binds handlers to be called
        when the menu item is selected.
        """
    ...
    ...
and called here
import wx
 
class HelloFrame(wx.Frame):
    """
    A Frame that says Hello World
    """
 
    def __init__(self, *args, **kw):
        # ensure the parent's __init__ is called
        super(HelloFrame, self).__init__(*args, **kw)
        ...
        ...
        # create a menu bar
        self.makeMenuBar()
Reply
#8
yes that's good :)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020