Jmac415
Jmac415

Reputation: 11

Dynamic multiple inheritance or mixins

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

Upvotes: 1

Views: 541

Answers (2)

0xc0de
0xc0de

Reputation: 8297

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.

Upvotes: 0

quamrana
quamrana

Reputation: 39384

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)

Upvotes: 1

Related Questions