I'm kind of new to Python, and I was trying to find a better way to transfer a bunch of messy class methods (which use member variables) into a separate module like Utils.py to clean things up. Method names must still be inherited by the base class, but they must also have access to the methods of the parnet class. I am detailing the background because I think there may be a better python way to solve this problem.
Basically, I need to do something like the following if I tried to do this through inheritance: (I played with super, but I could not solve it that way)
class Graph(GraphUtils): graph_size = 10 def print_size(self): print self.graph_size class GraphUtils(): def set_size(self, new_size) self.graph_size = new_size if __name__ == "__main__": g = Graph() print "Graph default size: " + str(g.graph_size) # This is 10 g.set_size(20) g.print_size() # I want it to print 20, but it'll print the default 10
I know that there is another way to unify the import of class methods and variables into another class, but I am running risk namespace conflicts.
The method that I used in a similar case, when a separate module was supposed to appear as an βadd-onβ in our library, looked like this: (the idea of ββan βadd-onβ arose from the desire to optionally distribute additional functionality for the Graph class, all this is related to licensing)
class Graph: ext = None graph_size = 10 def __init__(self): self.ext = Extension() self.ext._graph = self def set_size(self, new_size): self.graph_size = new_size class Extension: _graph = None def process(self): print "Processing graph size: " + str(self._graph.graph_size) if __name__ == "__main__": g = Graph() print "Graph default size: " + str(g.graph_size)
It's just interesting that you guys think this is the best approach or if it can be reasonably (safely) done in Python. (2.6 +)
Thanks!
source share