I am new to python (~ month) and I wish I had switched to it before (after several years of perl).
Problem . I want objects to have different functionality for the same method call based on their type. Methods are assigned at runtime based on a loaded module (which makes up all the objects).
Question I wanted to know if there was a popular design template that I could use instead of the one below, or if it already has a project template name (I, unfortunately, do not have a formal CS background, and knowing that this will help my documentation) ?
I have a class hierarchy (currently 26 of them with 3 base classes). Only base classes have some trivial methods (e.g. add_child), and each derived class only extends the base class with new data attributes (specific to the derived class), overriding methods if necessary (for example: __str __).
I am dealing with a tree (s) where the nodes have different classes. However, nodes must have the same names of certain methods ( stringify , print_tree , emit , eval , transform_X , etc.), thereby allowing the work with an easy / blind iterator. Each method can do something else, but the methods have the same name (for example, polymorphism).
First of all, I wanted to provide specific capabilities (methods) to nodes based on their type. I originally implemented this using a visitors template . But then I realized that I did not need this, given that I worked in Python.
In the example below, I have methods that are dynamically assigned to classes. Note that in the example below, the name of the iteration / recursion method call ( print_tree ) is different from the function name ( generic__print_tree ).
Finally, the main modules have this function, extend_types (), which is called during module initialization. Nodes are expected to do different things in the context of this module based on their type (rather than value). Assigned methods are inherited if not overridden.
edit: remote distracting information, made an example for the context of one module