adding methods at runtime and lambda

Mike msurel at comcast.net
Fri May 4 16:44:11 EDT 2007


On May 4, 2:05 pm, Peter Otten <__pete... at web.de> wrote:
> Mike wrote:
> > staticmethod makes the function available to the whole class according
> > to the docs. What if I only want it to be available on a particular
> > instance? Say I'm adding abilities to a character in a game and I want
> > to give a particular character the ability to 'NukeEverybody'. I don't
> > want all characters of that type to be able to wipe out the entire
> > planet, just the particular character that got the powerup.
>
> Static methods are for specialists, you don't need them. But then, your
> initial post looked like you were just exploring the possibilities...

Yeah, I'm just poking around.

>
> You can
>
> - have the Character.nuke_everybody() method check a self._can_nuke_eb flag

I don't like this one because it would require me to know every
ability everybody might ever have up front.

> - subclass the Character class with a NukingChar subclass and make only one
>   instance of that class

A possibility, I guess, but does this then mean I would need a new
class for every type of character? Probably not, but you would at
least need types grouped by general class, kind of like D&D characters
(Fighter, Magic User, etc.). It makes it harder for anybody to learn
anything they want.

> - add an instancemethod to one Character instance
>
> The simpler the approach you take the smarter you are ;)
>
> Peter

I just realized in working with this more that the issues I was having
with instancemethod and other things seems to be tied solely to
builtins like dict or object. I remember at some point just doing
something like:

x.fn = myfnFunction

and having it just work. If I do that with an instance of generic
object however, I get an AttributeError. So:

x = object()
x.fn = myFn

blows up. However, if I do

class nc(object):pass
x = nc()
x.fn = myFn

Then all is well.

checking for an ability on somebody is as simple as

'fn' in dir(x)

or

hasattr(x, 'fn')


I had thought this was a lot easier than I was making it out to be.
What I don't know is why using an object derived from object allows
you to dynamically add methods like this but the base object does not.
At this point it is more of a curiosity than anything, but if somebody
knows the answer off the top of their head, that would be great.

Thanks.




More information about the Python-list mailing list