Python – How to achieve inheritance when using just modules and vanilla functions in Python

designpythonpython-3.x

Python doesn't enforce any paradigm. It gives you freedom.
Python provides encapsulation at module level.

If I have a module A and have a module B with same interface. How do I sort of inherit B from A and override some functionality provided by B ?

Best Answer

When You import Y module, that imports functions from module X with from X import *, all functions from X are available as they were in Y ( You can thing of that, like pasting content of X into Y ).

And, when you have multiple defs, Python will take the last one. So to override functions You have just to redefine those function after you import X.

Also, when You want to use original function from X in Your Y, you can add aditional import X and access it with X.functionName().


Example:

module1.py

def foo():
   print "this will be overridden"
def bar():
   print "this will be preserved"

module2.py

from module1 import *
import module1

def foo():
   print "This was foo:"
   module1.foo()
   print "But it was overridden."

run.py

import module2

module2.foo()
module2.bar()

Example's result:

-> % python run.py 
This was foo:
this will be overridden
But it was overridden.
this will be preserved
Related Topic