(Easy ??) question about class definition

Greg Ewing greg at cosc.canterbury.ac.nz
Wed Mar 8 02:33:22 CET 2000


Gregoire Welraeds wrote:
> 
> When an item of my
> menu is selected, I want to execute some action... The action I want to
> perform is different for each item.

You can assign a method of any object to the 'action'
attribute of the entry, and the method will know what
object it belongs to. Try this out and see what gets
printed:

class entry:
  def __init__(self, name, action):
    self.name= name
    self.action= action
  def selected(self):
    self.action()

class thingy:
  def __init__(self, bauble):
    self.bauble = bauble
  def frobulate(self):
    print "Frobulating a thing with bauble =", self.bauble

my_thingy = thingy(42)

my_entry = entry("Frobulate", my_thingy.frobulate)

my_entry.selected()


I also corrected a couple of errors in class entry.
The selected() method was missing a self argument, and
you shouldn't be using exec() there, just calling the
action function directly.

Hope that helps,

-- 
Greg Ewing, Computer Science Dept,
+--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+



More information about the Python-list mailing list