Search code examples
pythoninheritancesubclasssuperclasssuper

Create sub class by calling super class python


I have a project where we are attempting to create an easier interface for several python GIS libraries. Based on our desired design schema, we want a user to only use/reference superclass methods without knowing the inner workings of subclasses.

Based on a file path extension passed to the superclass' constructor, is it possible to create a subclass, and then have a user's call to super methods be processed through the subclass?

In other words, if a user wants to make and interact with a car, can they give a car class the blueprints for a Ferrari and have the car "superclass" reference Ferarri "subclass" methods?

This seems a bit backwards in terms of design principals.


Solution

  • It sounds a lot like you want the factory pattern:

    In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class.

    But you shouldn't put the functionality in the constructor of Car. In your case Car is just a common interface for many kinds of different cars. As such the interface should not have to know anything about the implementations, and that includes the names of your subclasses.

    You would be much better off with a simple function that instantiates your objects:

    class Car(object):
        pass
    class Ferrari(Car):
        pass
    class Volkswagen(Car):
        pass
    def car_factory(blueprint, *args, **kwargs):
        if blueprint == "Ferrari":
            return Ferrari(*args, **kwargs)
        if blueprint == "Volkswagen":
            return Volkswagen(*args, **kwargs)
    

    or simply

    def car_factory(blueprint, *args, **kwargs):
        cars = {"Ferrari":Ferrari,
                "Volkswagen":Volkswagen}
        return cars[blueprint](*args, **kwargs)