473,387 Members | 1,517 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

classes and wx python

i know everyone keeps saying that one needs to be using classes and not just functions, but so far i haven't had any problems with functions aside from the fact that everyone's using them and when i see the help in any of the forums it's all in classes form,

my question is

im working basically with wx python, mainly doing interfaces for applications and nothing too fancy, connecting small databases and what not,

should i be migrating to classes? will it give me anything extra? i won't be using inheritance as i never saw it necessary in GUI's, but it keeps bothering me that i can't use the "self" thingy that everyone's using all around,

if i should actually do that, if i already have like a 1000 line code now i;m working on, is there an easier way to migrate, and understand what's going on?

i read a bunch of tutorials about classes, they're just plain confusing because i understand how they "hypothetically" be used in inheritance and all that, but i never really understand how i cld use it in daily life programming, especially with the level i;m working on,

really appreciate any comments or answers,

i just need to understand the whole fuss

any examples of a use of classes with wx that actually lead to something would be really appreciated

thanks

T
Sep 20 '09 #1
4 4188
"""
Okay, I'm not an expert with OOP myself, but I am a wxPython user and I do use classes. A very small sample code to work with for a bit of explanation. A simple class definition follows:
Expand|Select|Wrap|Line Numbers
  1. class MyObject(object):
  2.     def __init__(self, argument):
  3.         self.arg = argument
  4.  
The first line defines our class 'MyObject'. The value inside the parentheses is the object that our class inherits properties from. In current python style, I believe it is the practice to inherit from the sort-of default object type appropriately called 'object'. Remember that classes are objects, so you can specify a class to inherit properties from.

First, we override the built-in function __init__. Note that the first argument is 'self'. The first argument in every function we define in a class should be self (for a much better explanation, hit the docs! :))

This function gets called when the class is initialized (or is it called instantiated..?) along with any arguments. Thus it is usually a good starting place to get things done. Now, we set the passed argument to 'self.arg' this makes the attribute 'arg' accessible via self.

I'm going to add a few things to our code and give you an example, then I promise I will relate this to wxPython!
Expand|Select|Wrap|Line Numbers
  1. class MetaObject(object):
  2.     def __init__(self):
  3.         print "This is MetaObject!"
  4.  
  5. class MyObject(MetaObject):
  6.     def __init__(self, argument):
  7.         # We need to initialize the class we are inheriting from.
  8.         MetaObject.__init__(self)
  9.  
  10.         # Set our attribute.
  11.         self.arg = argument
  12.         print " - This is MyObject!"
  13.  
  14.     def print_arg(self):
  15.         print " - Argument was: %s." % self.arg
  16.  
  17. # Create an instance of our class MyObject.
  18. MyObj = MyObject(0)
  19. # Accessing a method.
  20. MyObj.print_arg()
  21. # Changing an attribute.
  22. MyObj.arg = "New arg!"
  23. print MyObj.arg
  24.  
If you run this, it would produce this output:

This is MetaObject!
- This is MyObject!
- Argument was: 0.
New arg!

Does this make sense? Let's look at it as applied to wxPython.

It's important to note that there are many uses and applications for classes these are just a couple of (I think) relevant examples. I often find the need for creating my own dialogs and classes are a perfect solution. What I do is create a class and have it inherit from the wx.Dialog class. Then in __init__ I initialize wx.Dialog and then go about setting up my dialog. Here's an example from a project of mine.
Expand|Select|Wrap|Line Numbers
  1. class EditDialog(wx.Dialog):
  2.     """The Edit Dialog."""
  3.     def __init__(self, parent, ID, title, pos=wx.DefaultPosition, \
  4.                  size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, \
  5.                  data=("","")):
  6.         """Init the edit dialog."""
  7.         wx.Dialog.__init__(self, parent, ID, title, pos, size, style)
  8.         self.txtKey = wx.TextCtrl(self, -1, data[0])
  9.         self.txtValue = wx.TextCtrl(self, -1, data[1], style=wx.TE_MULTILINE)
  10.         self.lblKey = wx.StaticText(self, -1, "Key", size=(50, 15), \
  11.                                     style=wx.ALIGN_RIGHT)
  12.         self.lblValue = wx.StaticText(self, -1, "Value", size=(50, 15), \
  13.                                       style=wx.ALIGN_RIGHT)
  14.  
  15.         st = wx.StaticText(self, -1, " ")
  16.  
  17.         edit_sizer = wx.BoxSizer(wx.VERTICAL)
  18.         h_sizer = wx.BoxSizer(wx.HORIZONTAL)
  19.         h_sizer.Add(self.lblKey, 0, wx.RIGHT, 4)
  20.         h_sizer.Add(self.txtKey, 1, wx.EXPAND)
  21.         edit_sizer.Add(h_sizer, 0, wx.EXPAND | wx.ALL, 1)
  22.  
  23.         h_sizer = wx.BoxSizer(wx.HORIZONTAL)      
  24.         h_sizer.Add(self.lblValue, 0, wx.RIGHT, 4)
  25.         h_sizer.Add(self.txtValue, 1, wx.EXPAND)
  26.         edit_sizer.Add(h_sizer, 1, wx.EXPAND | wx.ALL, 1)
  27.  
  28.         btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
  29.         st = wx.StaticText(self, -1, " ")
  30.         btn_sizer.Add(st, 1, wx.EXPAND, 0)
  31.         btn_okay = wx.Button(self, wx.ID_OK)
  32.         btn_cancel = wx.Button(self, wx.ID_CANCEL)
  33.         btn_sizer.Add(btn_okay, 0)
  34.         btn_sizer.Add(btn_cancel, 0)
  35.  
  36.         edit_sizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 1)
  37.         self.SetSizer(edit_sizer)
  38.         self.Bind(wx.EVT_BUTTON, self.OnOk)
  39.  
  40.     def OnOk(self, evt):
  41.         """End dialog with the corresponding ID."""
  42.         self.key = self.txtKey.GetValue()
  43.         self.value = self.txtValue.GetValue()
  44.         self.EndModal(evt.GetId())
  45.  
  46.  
This is a simple Dialog containing two TextCtrls and their corresponding StaticText labels with 'OK' and 'Cancel' buttons at the bottom. Users can edit the values. OnOk() is the function to look at. It ends the Dialog by callingEndModal() and passing it the argument that identifies the button that was clicked.

And the corresponding code that utilizes this class might look like this:
(from another class..)
Expand|Select|Wrap|Line Numbers
  1. def EditItem(self, key, value):
  2.     """ Display the edit dialog. """
  3.     dlg = EditDialog(self, -1, "Edit key/value..", data=(key, value))
  4.     if dlg.ShowModal() == wx.ID_OK:
  5.         data = (dlg.key, dlg.value)
  6.  
This is just an example function but hypothetically it would be called from some other piece of code and sent two arguments, key and value. We instantiate our custom Dialog sending it the required wx arguments and our argument 'data' which is a tuple containing 'key' and 'value'. The next line is where our Dialog gets shown with dlg.ShowModal() and if the 'OK' button was clicked, we set the variable 'data' to the values of the Dialog's attributes 'key' and 'value' which we set in the method OnOk(). So we displayed our dialog, and allowed the user to edit some values and then retrieved those values. (Although the example doesn't do
anything very interesting with this..)

Now we have a custom wx.Dialog! I'm sure you can see how useful this is as you can apply the concept to any widget and non-widgets alike!

Another big, big benefit of using classes is being able to more efficiently reuse code. If you have been using wxPython then you have been using classes the entire time! Everytime you make a frame and change its properties and use its methods you are interacting with a class. The difference here is we are using that mechanism to our advantage and defining behavior ourself!

I really hope that this was coherent and that it answers some questions and helps you along in your code. In my experience I felt it took me a long time, and several attempts to truly start to understand OOP and classes. I think you will find them extremely helpful in your wx
programming, I know I do.

If you need any clarification, please ask! The best resources you have are the python/wxpython docs and the wxPython demo. Use them!
Sep 20 '09 #2
thank you so much for all this information!

it took me a while to read and really understand what's going on, and i think i understand a bunch of it, but here come my clarification questions..,

# def __init__(self, parent, ID, title, pos=wx.DefaultPosition, \
# size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, \
# data=("","")):
# """Init the edit dialog."""
# wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

so the initializer which contains all the text boxes and stuff would be just one of the functions inside that class? no different? aside from the fact that it is the all mighty __init__?

so comes another question, in the app that i would have, the main frame that would initialize the app would be the highest class under which everything resides? or would it be a stand alone class? and how would i call this main frame app? define an instance and simply call it? (in the demo, it shows the code but not how it was called) unless it was this part? because i still can't understand it :S

Expand|Select|Wrap|Line Numbers
  1. if __name__ == '__main__':
  2.     import sys,os
  3.     import run
  4.     run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
  5.  

i know the fact that everytime i'm using a frame or dialog, i am accessing the class itself and manipulating its values, but i still feel i can still do that with having the dialog as a function to which i define the values of a dialog inside, and i think that is because i did not come across an example where a function will not do the job and i need a class instead, and until that happens, i wont really get it (with the example you've mentioned, isn;t it possible to define it in a function and call the function?)

now i know i need to move to classes, in order to understand what i;m missing, so i have a very lame question here, has anyone made a tool to convert from functions to classes? because i really feel the difference if very systematic,

otherwise, i have already gone through 500 lines of code, is it worth making the move now manually? or should i just let it be since it basically works with almost no problems so far?

im sorry if my reply seems very scattered, but that's kinda how my thoughts are working now,

you;ve been of tremendous help! i bow before u sensei

T



EDIT: i understand how classes may come in handy as a data structure, to store watever inside and then access them and change values individually, but haven;t gotten it in any other way :S just thought i'd mentions this
Sep 20 '09 #3
I think this should help. It is a small demo of wxPython using OOPish concepts.

http://colinbarnette.net/code/wxdemo.py

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. import wx
  3.  
  4. class MainFrame(wx.Frame):
  5.     def __init__(self, parent, ID, title, pos=wx.DefaultPosition,
  6.                  size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
  7.         wx.Frame.__init__(self, parent, ID, title, pos, size, style)
  8.  
  9.         label = "Click the button and change this text!\n(Or use the Menu..)"
  10.         # Initalize some controls..
  11.         self.panel = wx.Panel(self, -1, style=wx.BORDER_SUNKEN)
  12.         self.text = wx.StaticText(self.panel, -1, label,
  13.                                   style=wx.ALIGN_CENTER | wx.ST_NO_AUTORESIZE)
  14.         self.button = wx.Button(self.panel, -1, "Click me!")
  15.         self.panel.SetBackgroundColour(wx.WHITE)
  16.  
  17.         # Initialize the menubar
  18.         menubar = wx.MenuBar()
  19.         self.menu = wx.Menu()
  20.         self.menu.Append(101, "&Edit text..", "Edit text")
  21.         self.menu.AppendSeparator()
  22.         self.menu.Append(102, "&Close", "Close")
  23.         menubar.Append(self.menu, "&Menu")
  24.         self.SetMenuBar(menubar)
  25.  
  26.         # Initialize the statusbar
  27.         self.CreateStatusBar()
  28.         self.SetStatusText("")
  29.  
  30.         # Initialize the sizers and fill them
  31.         sizer = wx.BoxSizer(wx.HORIZONTAL)
  32.         st = wx.StaticText(self.panel, -1, "")
  33.         sizer.Add(st, 1, wx.EXPAND, 0)
  34.         sizer.Add(self.button, 0, 0, 0)
  35.         st = wx.StaticText(self.panel, -1, "")
  36.         sizer.Add(st, 1, wx.EXPAND, 0)
  37.  
  38.         st = wx.StaticText(self.panel, -1, "")
  39.         vsizer = wx.BoxSizer(wx.VERTICAL)
  40.         vsizer.Add(st, 1, wx.EXPAND, 0)
  41.         vsizer.Add(self.text, 1, wx.EXPAND | wx.ALL, 4)
  42.         vsizer.Add(sizer, 1, wx.EXPAND | wx.ALL, 4)
  43.  
  44.         self.panel.SetSizerAndFit(vsizer)
  45.  
  46.         # Bind our events.
  47.         self.Bind(wx.EVT_BUTTON, self.OnButton)
  48.         self.Bind(wx.EVT_MENU, self.OnMenu)
  49.  
  50.     def OnMenu(self, event):
  51.         if event.GetId() == 101:
  52.             self.ShowEditDialog()
  53.         else:
  54.             self.OnClose(event)
  55.  
  56.     def OnButton(self, event):
  57.         if event.GetId() == self.button.GetId():
  58.             self.ShowEditDialog()
  59.  
  60.     def OnClose(self, event):
  61.         self.Close()
  62.  
  63.     def ShowEditDialog(self):
  64.         dlg = EditDialog(self, -1, "Edit the StaticText..")
  65.         if dlg.ShowModal() == wx.ID_OK:
  66.             self.text.SetLabel(dlg.value)
  67.             self.SetStatusText("Label changed to \"" + dlg.value + "\".")
  68.  
  69. class EditDialog(wx.Dialog):
  70.     def __init__(self, parent, ID, title, pos=wx.DefaultPosition, 
  71.                  size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
  72.         wx.Dialog.__init__(self, parent, ID, title, pos, size, style)
  73.  
  74.         # Initialize some controls.
  75.         self.text = wx.TextCtrl(self, -1, "")
  76.         self.okay = wx.Button(self, wx.ID_OK)
  77.         self.cancel = wx.Button(self, wx.ID_CANCEL)
  78.  
  79.         st = wx.StaticText(self, -1, "")
  80.         label = wx.StaticText(self, -1, "Enter text:")
  81.  
  82.         hsizer = wx.BoxSizer(wx.HORIZONTAL)
  83.         hsizer.Add(st, 1, wx.EXPAND, 0)
  84.         hsizer.Add(self.okay, 0, wx.EXPAND, 0)
  85.         hsizer.Add(self.cancel, 0, wx.EXPAND, 0)
  86.  
  87.         sizer = wx.BoxSizer(wx.VERTICAL)
  88.         sizer.Add(label, 0, wx.EXPAND | wx.ALL, 4)
  89.         sizer.Add(self.text, 0, wx.EXPAND | wx.ALL, 4)
  90.         sizer.Add(hsizer, 0, wx.EXPAND | wx.ALL, 4)
  91.  
  92.         self.SetSizerAndFit(sizer)
  93.         self.Bind(wx.EVT_BUTTON, self.OnButton)
  94.  
  95.     def OnButton(self, event):
  96.         self.value = self.text.GetValue()
  97.         self.EndModal(event.GetId())
  98.  
  99. if __name__ == "__main__":
  100.     app = wx.App(redirect=False)
  101.     mainframe = MainFrame(None, -1, "wxPython OOP Demo", size=(225, 200))
  102.     mainframe.Show()
  103.     app.MainLoop()
  104.  
  105.  
Sep 21 '09 #4
thank you so much for your reply,

but i dont think ill be using it because this the program is almost done, and it's basically working flawlessly,

maybe if i start something new

you've been of tremendous help my friend

thank you sir Hackworth
Sep 30 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

145
by: David MacQuigg | last post by:
Playing with Prothon today, I am fascinated by the idea of eliminating classes in Python. I'm trying to figure out what fundamental benefit there is to having classes. Is all this complexity...
7
by: Bo Peng | last post by:
Dear Python group: I am planning on an application that involves several complicated C++ classes. Basically, there will be one or two big data objects and some "action" objects that can act on...
1
by: Eric Wilhelm | last post by:
Hi, By new-style classes, I'm referring to the changes which came into 2.2 as a result of PEP 252 and 253. I discovered this problem when trying to use the Perl Inline::Python module with a...
12
by: David MacQuigg | last post by:
I have what looks like a bug trying to generate new style classes with a factory function. class Animal(object): pass class Mammal(Animal): pass def newAnimal(bases=(Animal,), dict={}):...
16
by: Simon Wittber | last post by:
I've noticed that a few ASPN cookbook recipes, which are recent additions, use classic classes. I've also noticed classic classes are used in many places in the standard library. I've been...
2
by: Xah Lee | last post by:
© # -*- coding: utf-8 -*- © # Python © © # in Python, one can define a boxed set © # of data and functions, which are © # traditionally known as "class". © © # in the following, we define a...
11
by: Ryan Krauss | last post by:
I have a set of Python classes that represent elements in a structural model for vibration modeling (sort of like FEA). Some of the parameters of the model are initially unknown and I do some...
5
by: Alex | last post by:
Hi, this is my first mail to the list so please correct me if Ive done anything wrong. What Im trying to figure out is a good way to organise my code. One class per .py file is a system I like,...
6
by: s99999999s2003 | last post by:
hi i come from a non OO environment. now i am learning about classes. can i ask, in JAva, there are things like interface. eg public interface someinterface { public somemethod (); .... ... }...
11
by: allendowney | last post by:
Hi All, I am working on a revised edition of How To Think Like a Computer Scientist, which is going to be called Think Python. It will be published by Cambridge University Press, but there...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.