How to inherit a class' methods and have them access self member variables in python -
I'm new to the python, and I'm trying to understand the best way to migrate a group of messy To clean things, classroom methods (which use the members' variables), method names in a separate Utilx.py type module, still need to be inherited by the base class, but they have access to the methods of the pannet class Should also be. I am reporting the background because I think there can be a better dragon way to solve it.
Actually I have to do something like the following, if I was trying to do this through heirs: they played with super, but I have not been able to solve it in this way 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 10 g.set_size (20) G.print_size () # I want to print it 20, but this Default 10
I know that the only way to import classes and variables into another category, but I run risk namespace collisions.
There is a technique I used in a similar case, where a separate module was needed to appear in our library as an add-on: ('add-on' idea The functionality of nal in the graph class is related to all the licensing.)
graph: ext = any graph_size = 10 def __init __ ( Self): self.ext = extension () self.ext._graph = self-set dff_size ( Self, new_size): self.graph_size = new_size class extension: _graph = any df process (self): print "processing graph size:" + str (self._graph.graph_size) if __name__ == "__main__": G = graph () Print "Graph default size:" + str (g.graph_size) # this 10g .set_size (20) g.ext.process () # Output: Graph Size Processing: 20
Thank you!
Its solution is to define variables in the __init __ () method of the class, and the inherited object Be sure to start.
__ init (__) is a 'magic' class method that is called when a new object class definition. New style python classes (recommended) for class GraphUtils (object) #Orit object: # __Int (__) override magic-method. Def __init __ (self): Start your inherited object by executing your __init __ () method. Super (GraphUtils, self) .__ init (__) def set_size (self, new_size): self.graph_size = new_size # GraphUtils Class Graph (GraphUtils): def __init __ (self): # Start the inherited GraphUtils object. Super (graph, self) .__ init (__ ()) Announce graph_ass variables on the creation of a new graph object. Self.graph_size = 10 def print_size (self): print self.graph_size if __name__ == "__main__": g = graph () # String Connection is recommended to use str.format (instead of print) "Graph default size : {} ". Format (g.graph_size) # "Graph default size: 10" g.set_size (20) g.print_size () # will print it will print 20
Comments
Post a Comment