Adding methods to a class
I spent some time tonight trying to build a system to handle plug-ins. I’ve been working on an IRC bot, and I’d like to be able to load individual modules to add functionality to it. Definitely one of the trickier projects that I’ve worked on up to this point. Although, in the end, it ended up being rather simple.
Here’s my code for returning a list of functions from a class:
def getfunctions(self, module):
flist = []
for key, value in module.__dict__.items():
if type(value) is types.FunctionType:
flist.append(value)
return flist
And here’s how I’m adding methods to a class:
def add_method(self, parent, method, name=None):
print "Adding method...", method.func_name
bound_method = new.instancemethod(method, parent, parent)
setattr(parent, method.func_name, bound_method)
At this point, I have a nice PluginManager class that I can reuse in the future to handle loading .py files and adding the functions to a specified class as new methods. I’ll clean up the code a bit and post it for those who are interested.