Reputation: 20300
I have a generic class UsbLib
which I want to use as a simple clean API. However I want this class to become an other class depending on the circumstances.
class UsbLib:
def __new__(self):
if this_is_latest_ubuntu():
return UsbUDisks2() # Doesn't work
class UsbUDisks2(UsbLib):
def list_devices():
print("Listing devices..")
So for example if I am running the below code in Ubuntu
lib=UsbLib()
I want it to internally resolve to
lib=UsbUDisks2()
How can I do this?
Upvotes: 0
Views: 40
Reputation: 53603
You are looking for something called Factory pattern. In simple terms, you do not instantiate the classes directly, but rather call a function which does the logic and returns the right class/object to you for use.
def factory_function():
if(something):
return Class1()
else:
return Class2()
CC = factory_function()
...
...
Or even nicer, use a common parent and use a static method in that parent to get the right child
class ClassFather:
@staticmethod
def factory():
if(something):
return Class1()
else:
return Class2()
class Class1(ClassFather): # not really necessary to have inheritance, only if common functionality
pass
class Class2(ClassFather): # not really necessary to have inheritance, only if common functionality
pass
Upvotes: 1
Reputation: 60065
You better do it with some sort of factory pattern.
In simplest form:
def createUsbLib(params):
if this_is_latest_ubuntu():
return UsbUDisks2()
else:
return UsbLib()
Upvotes: 1