(Easy ??) question about class definition

Quinn Dunkan quinn at drachma.ugcs.caltech.edu
Wed Mar 1 19:56:49 CET 2000


On Tue, 29 Feb 2000 18:13:37 +0100 (CET), Gregoire Welraeds <greg at perceval.be>
wrote:
>Hello again,
>
>I think the problem I have is common in OOP... but I don't have any
>beginning of solution.
>
>I got the following problem. Imagine i want to manage a menu. So I define
>2 classes. First one is the class menu and is basicly a list of entry. The
>second is the item class representing each menu entry. 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. So I get the following
>
>class entry:
>	def __init__(self, name, action):
>		self.name= name
>		self.action= action
>	def selected():
>		exec(self.action)
>	[some methods]
>
>class menu:
>	def __init__(self, name):
>		self.name= name
>		self.list=[]
>	[some methods]
>...
>
>Now self.action is a reference to something I have to define elsewhere. It
>could be a separate function... but then, the function is not bound to a
>class as method are and everybody can use it. And I don't want to have
>each action to be define in the class. 
>thus the problem is that each action i bound with an instance of the class
>item.
>I know there are some solutions in Design Pattern but I don't know howto
>implement this in Python.

Hmm, well, I've never read anything on design patterns (should though, any book
recommendations?), but why not just make entry an abstract base?  E.g.:

class MenuEntry:
    name = 'no name'
    def __init__ etc.
    def selected(self):
        say 'there is no action associated with this entry'
        (or maybe self.grayed_out = 1 in __init__)

class RescanArchive(MenuEntry):
    name = 'Rescan CIA Archive...'
    def selected(self):
        etc.


I haven't done much with Tkinter or other gui toolkits, but I know Tkinter at
least uses a lot of callbacks, which implies it's closer to your approach.

And I imagine your approach is constrained anyway but what toolkit you're
using.



More information about the Python-list mailing list