1

I am trying to understand how to implement multiple inheritance or MixIns in my program.

My thinking is that I have a Car class that uses MixIns to add methods from difference performance boosters like cold air intake and supercharger. So something like the below although I know this doesn't work.

car1 = Car(Turbocharger, ColdAirIntake)
car2 = Car(Supercharger)
car3 = Car(Nitrous)

I found this example, but wasn't sure if this was the proper way to do what I am thinking.

Dynamically mixin a base class to an instance in Python

Jmac415
  • 11
  • 1
  • Rather than subclassing, it might be more appropriate to pass a list of instances of the various component types to `Car.__init__`, e.g. `car1 = Car(Turbocharger(), ColdAirIntake())`. It's hard to say without knowing how all the classes are defined and how they are intended to fit together. – chepner Dec 23 '20 at 17:01

2 Answers2

1

You can make instances by dynamically defining your car class:

def make_car(*bases):
    class dynamic_car(*bases, Car):
        pass
    return dynamic_car()

car1 = make_car(Turbocharger, ColdAirIntake)
car2 = make_car(Supercharger)
car3 = make_car(Nitrous)
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

Not sure if I understand you completely, but if you want to just understand what you have mentioned, look at this simple example:

class Turbocharger(dict):
    # Define any class attributes.
    def __init__(self):
        # Define any instance attributes here.
        super().__init__()
 
    def __call__(self, *others):
        for other in others:
            # You'd want to check if it's a mixin, isinstance()?
            self.update(other)


class Supercharger(dict):
    # Same stuff here.

Basically each of these mixins just 'update' themselves with other mixins passed as arguments to the __call__. These classes just adds some syntactic sugar.

0xc0de
  • 8,028
  • 5
  • 49
  • 75
  • Now when I read the question again after answering it, I am confused even more about your expected behaviour. This can be way off, but I'll keep it here, if it helps anyone. I have never came across a situation myself where I'd do this, but I might have seen very little :D . – 0xc0de Dec 23 '20 at 17:00