Defining class methods outside of classes
Peter Otten
__peter__ at web.de
Thu May 4 02:07:28 EDT 2006
Lord Landon wrote:
> Hi, I'm working on a bot written in python. It will consist of a
> mostly empty class that will then call a loader which in turn defines
> functions and adds them to the class. At the moment, I do this by
> using execfile(file,globals()) and calling a load(bot) method defined
> in every "module" which takes the functions defined in that perticular
> module and does bot.function=function. The problem with that is when I
> call bot.function() self doesn't get passed as an argument to the
> function. Is there anything I can do to sort this besides calling
> bot.function(bot, ...) everytime?
Either add the method to the class or make it an instance method.
>>> class Bot(object):
... def __init__(self):
... self.name = "bot"
...
>>> bot = Bot()
>>> def method(self): print "hello from", self.name
...
>>> Bot.greet = method
>>> bot.greet()
hello from bot
>>> import new
>>> bot.hello = new.instancemethod(method, bot)
>>> bot.hello()
hello from bot
Peter
More information about the Python-list
mailing list