473,609 Members | 1,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

classes and wx python

75 New Member
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 4197
Hackworth
13 New Member
"""
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
askalottaqs
75 New Member
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.DefaultP osition, \
# size=wx.Default Size, style=wx.DEFAUL T_FRAME_STYLE, \
# data=("","")):
# """Init the edit dialog."""
# wx.Dialog.__ini t__(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
Hackworth
13 New Member
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
askalottaqs
75 New Member
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
6285
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 unecessary? Here is an example of a Python class with all three types of methods (instance, static, and class methods). # Example from Ch.23, p.381-2 of Learning Python, 2nd ed. class Multi:
7
2387
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 the data. I would like to use a script language to control the interaction between these c++ objects. I become interested in Python since it can load C++ objects and can even extend C++ classes. However, I am not quite sure to what extent can...
1
1833
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 python class that was inheriting from the new builting 'object' class like so: class MyClass(object): The problem is in detecting that this class should be treated as a class
12
3812
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={}): class C(object): pass C.__bases__ = bases dict = 0
16
2050
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 using new-style classes since Python 2.2, and am suprised people are still using the classic classes. Is there a legitimate use for classic classes that I am not aware of?
2
1682
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 set of data © # and functions as a class, and name it xxx © class xxx:
11
1524
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 system identification to determine the parameters. After I determine these unknown parameters, I would like to substitute them back into the model and save the model as a new python class. To do this, I think each element needs to be able to read...
5
1650
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, keeps stuff apart. If I do that, I usually name the .py file to the same as the class in it. File: Foo.py *********************** class Foo:
6
1816
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 (); .... ... } In python , how to implement interface like the above? is it just
11
1433
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 will still be a free version under the GNU FDL. You can see the latest version at thinkpython.com; I am revising now,
0
8139
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8091
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8579
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8232
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5524
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4098
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2540
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1686
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1403
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.