duality_
duality_

Reputation: 18756

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?

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.

Upvotes: 7

Views: 10508

Answers (5)

Ekrem Dinçel
Ekrem Dinçel

Reputation: 1141

I wanted to inherit from a module before, and I did it like so:

import json

class custom_json(): pass

for i in json.__all__:
    setattr(custom_json, i, getattr(json, i))

It isn't a good practice, but it works.

If you want to override some attributes, then you can use this:

import json

class custom_json():
    def dump():
        pass
    
for i in json.__all__:
    if not hasattr(custom_json, i):
        setattr(custom_json, i, getattr(json, i))

Upvotes: 1

Nabin
Nabin

Reputation: 11776

class Base():
    .....

class derived(Base):
    ......

But this is inheriting class...

Upvotes: 0

Arunmu
Arunmu

Reputation: 6901

Let me give you an example:

Base.py

import os
import sys
config = dict()
config['module_name'] = "some_xyz_thing"
config['description'] = "Implements xyz functionality"

Derived.py

from Base import config
config['module_name'] = "som_more_xyz_functionality"

This way you can use inheritance at module level

Upvotes: -2

Mike Graham
Mike Graham

Reputation: 76683

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.

Upvotes: 3

unutbu
unutbu

Reputation: 879361

Modules can sometimes be used to implement Singletons, but they aren't meant to be a replacement for classes. You can only import the module once, while a class can have multiple instances.

If you need inheritance, use a class.

Upvotes: 1

Related Questions