Skip to content Skip to sidebar Skip to footer

Dynamic Method Binding With Inheritance In Python

I am new to python (~ a month), and I wish I had switched to it sooner (after years of perl). Problem: I want objects to have different functionality to the same method call base

Solution 1:

Problem Summary

Ignoring the irrelevant details, the problems here can be summed up as follows:

There is one base class and many derived classes. There is a certain functionality which should apply to all of the derived classes, but depends on some external switch (in the question: choice of "main module").

The idea in the question is to monkeypatch the base class depending on the switch.

Solution

Instead of that, the functionality which depends on the external switch should be separated.

In example:

# There is a base class:classASTNode(object):
    pass# There are many derived classes, e.g.:classASTVar(ASTNode):
    pass# One implementation of function stringify or another# should be defined for all objects, depending on some external factordefstringify1(node):
    # somethingdefstringify2(node):
    # something else# Depending on whatever, choose one of them:

stringify = stringify1

This is now used just a little bit differently than in the original code: intead of node.stringify(), there is now stringify(node). But there is nothing wrong with that.

BTW...

Maybe it would be more pleasing to the eye to use a class:

class NodeHandler1(object): def print_tree(node): # do something

defstringify(node):
    # do something

...

But that is not required at all.

The Moral

Do not monkeypatch. That is always bad design.

Post a Comment for "Dynamic Method Binding With Inheritance In Python"