Pithikos
Pithikos

Reputation: 20300

Python class substituion with other class?

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

Answers (2)

Itay Moav -Malimovka
Itay Moav -Malimovka

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

Andrey
Andrey

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

Related Questions