(Easy ??) question about class definition
Gordon McMillan
gmcm at hypernet.com
Tue Feb 29 12:26:40 EST 2000
Gregoire Welraeds writes:
>
> I think the problem I have is common in OOP... but I don't have any
> beginning of solution.
That's because Python makes it too easy ;-).
> 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]
Not quite. Change that to:
def selected(self):
self.action()
Now the actions can be functions:
def action1():
print "action1"
e1 = entry("First", action1)
or bound methods:
class A:
....
def action(self):
print "A.action"
a = A()
e2 = entry("Second", a.action)
That's all there is to it.
> 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.
>
> thanks for your answer.
>
> --
> Life is not fair
> But the root password helps
> --
>
> Gregoire Welraeds
> greg at perceval.be
> Perceval Development team
> -------------------------------------------------------------------------------
> Perceval Technologies sa/nv Tel: +32-2-6409194
> Rue Tenbosch, 9 Fax: +32-2-6403154
> B-1000 Brussels general information: info at perceval.net
> BELGIUM technical information: helpdesk at perceval.net
> URL: http://www.perceval.be/
> -------------------------------------------------------------------------------
>
>
>
>
> --
> http://www.python.org/mailman/listinfo/python-list
- Gordon
More information about the Python-list
mailing list