Reputation: 526
I am making an IRC bot with Twisted and I have run into a problem. I want to import functions from a seperate file into my main class (the one that inherits irc.IRCClient) so they can be used as methods. I have thought of two possible solutions, but they both seem a bit newbish and they both have problems.
Solution 1: Put the functions in a class in a separate file, import it into my main file and make my main class inherit the class. The problem with this solution is that I will end up inheriting quite a few classes and I have to modify my main class each time I make a new module for the bot.
Solution 2: Put the functions in a separate file, import it into my main file and assign each of the imported functions to a variable. This is annoying because I would have to set a variable in my main class for each of the methods I want the class to import from somewhere else.
importthis.py
class a():
def somemethod(self):
print "blah"
main.py
import importthis
class mainClass(irc.IRCClient):
thisisnowamethod = importthis.a()
As you can see, both methods (no pun intended) require a lot of stupid work to maintain. Is there a smarter way to do this?
Upvotes: 2
Views: 290
Reputation: 184290
class mainClass(irc.IRCClient):
from othermodule import a, b, c
# othermodule.a, b, and c are now methods of mainClass
from anothermodule import *
# everything in anothermodule is now in mainClass
# if there are name conflicts, last import wins!
This works because import
simply imports symbols to a namespace and doesn't much care what kind of namespace it is. Module, class, function -- it's all copacetic to import
.
Of course, the functions in othermodule
must be written to accept self
as their first argument since they will become instance methods of mainClass
instances. (You could maybe decorate them using @classmethod or @staticmethod, but I haven't tried that.)
This is a nice pattern for "mix-ins" where you don't necessarily want to use multiple inheritance and the headaches that can cause.
Upvotes: 2
Reputation: 49105
I think the question that needs to be answered for each of these imported methods is, does it act on the state of the object? The answer seems to be no -- they don't know about your main class, and therefore should not be methods on the main class. And I don't think there's an IS-A relationship between your main class and those that it would inherit from.
But is your problem that you want callers to have access to these methods? A good solution is to just make these methods available as a module that can be imported.
Upvotes: 1