[Tutor] Function assignment (was: Re: Function type?)

Jeff Shannon jeff@ccvcorp.com
Thu Jun 12 14:09:01 2003


Bob Gailer wrote:

> At 06:46 AM 6/12/2003 -0700, Zak Arntson wrote:
>
>> > class Item:
>> >     def attach(self, name, func):
>> >         eval('self.%s = new.instancemethod(func, self, Item)' % name)
>
>
> eval is for expressions. Alas, assignment is a statement rather than 
> an expression.
> Try exec instead.


Better yet, don't use either -- use setattr().

    def attach(self, name, func):
        setattr(self, name, new.instancemethod(func, self, Item))

(Note -- I haven't tested that your use of instancemethod() is correct, 
I'm only pointing out that setattr() is a better solution here than 
exec/eval() is.  There's almost *always* a better solution than 
exec/eval() ... )

Jeff Shannon
Technician/Programmer
Credit International