Reputation: 1428
The following is the example I would like to do
I have different vehicle for Two-Door car, Bus, Van but they are the inherited from 'Vehicle'. What I want to do is to create a base class ('Vehicle') so everyone need to follow. And then people can build their own plugins (e.g. Bus, Van).
Then other users would use the plugin like this
my_vehicle = Vehicle('bus')
Then the bus class will be used.
I got the idea but I have no idea how should it be implemented?
Thanks in advance
Upvotes: 0
Views: 317
Reputation: 19030
Another option is to use an already existing plugin library such as stevedore
This gives you:
Upvotes: 0
Reputation: 20518
You can use a metaclass for this:
class VehicleType(type):
registry = {}
def __init__(self, name, bases, attrs):
self.registry[name.lower()] = self
def __call__(self, name):
cls = self.registry[name]
inst = cls.__new__(cls)
inst.__init__()
return inst
class Vehicle(object):
__metaclass__ = VehicleType
class Car(Vehicle):
pass
car = Vehicle("car")
print(type(car)) # <class '__main__.Car'>
This works by having the class inheritance process register the class in the metaclass, then overriding the behavior of calling Vehicle
so that it dynamically dispatches to the appropriate class.
Upvotes: 1