(Easy ??) question about class definition
Ken Seehof
kens at sightreader.com
Tue Feb 29 15:02:26 EST 2000
You forgot your self.
>>> def f():
... print 'spam'
...
>>>
>>> class entry:
... def __init__(self, name, action):
... self.name= name
... self.action= action
... def selected(self):
... apply(self.action, ())
...
>>> def f():
... print 'spam'
...
>>> e = entry('spammer', f)
>>>
>>> e.selected()
spam
>>>
Also, you can use apply instead of exec, and get the added bonus of being able to
add parameters later.
Gregoire Welraeds 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.
>
> 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/
> -------------------------------------------------------------------------------
More information about the Python-list
mailing list