Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend (inheritance) a module in Python?

So I hear that modules are very pythonic and I structure my code with modules a lot and avoid classes.

But now I'm writing a module Formula that has a lot of the same functionality as the module Car. How should I handle that?

  • Duplicate code in both modules?
  • Convert to classes?
  • Refactor code to add a third, parent module Vehicle and import methods and variables that I need?

The third looks good, the only downside that I see is that there are some variables that are specific to a module (e.g. top_speed), but the functions in the parent module Vehicle need to access those specific variables.

like image 981
duality_ Avatar asked Aug 10 '26 17:08

duality_


1 Answers

A module is an instance, not a class, so you can't inherit from it any more than you can inherit from 6.

If your stuff has state, you should have classes, not modules.

If you have two modules that need the same stuff, then it either a) one of them should have it and the second should use the first, or b) they should both get it from a third module.

Module names are typically lowercase, since Uppercase/CamelCase names indicate classes.

like image 115
Mike Graham Avatar answered Aug 13 '26 07:08

Mike Graham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!