On May 3, 11:25 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Thu, 03 May 2007 16:52:55 -0300, Mike <[EMAIL PROTECTED]> escribió: > > > I was messing around with adding methods to a class instance at > > runtime and saw the usual code one finds online for this. All the > > examples I saw say, of course, to make sure that for your method that > > you have 'self' as the first parameter. I got to thinking and thought > > "I have a lot of arbitrary methods in several utility files that I > > might like to add to things. How would I do that?" And this is what I > > came up with: > > I don't see the reason to do that. If you have a function that does not > use its "self" argument, what do you get from making it an instance method? > If -for whatever strange reason- you want it to actually be a method, use > a static method: > > py> def foo(x): > ... print "I like %r" % x > ... > py> class A(object): pass > ... > py> a = A() > py> A.foo = staticmethod(foo) > py> a.foo() > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: foo() takes exactly 1 argument (0 given) > py> a.foo("coffee") > I like 'coffee' > py> A.foo("tea") > I like 'tea' > > -- > Gabriel Genellina
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. -- http://mail.python.org/mailman/listinfo/python-list