Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pick a subclass based on a parameter

Tags:

python

oop

I have a module (db.py) which loads data from different database types (sqlite,mysql etc..) the module contains a class db_loader and subclasses (sqlite_loader,mysql_loader) which inherit from it.

The type of database being used is in a separate params file,

How does the user get the right object back?

i.e how do I do:

loader = db.loader()

Do I use a method called loader in the db.py module or is there a more elegant way whereby a class can pick its own subclass based on a parameter? Is there a standard way to do this kind of thing?

like image 752
Mike Vella Avatar asked Sep 01 '11 16:09

Mike Vella


People also ask

What is __ Init_subclass __ in Python?

The __init_subclass__ class method is called when the class itself is being constructed. It gets passed the cls and can make modifications to it. Here's the pattern I used: class AsyncInject: def __init_subclass__(cls, **kwargs): super().

What is __ new __ in Python?

__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self . Now, I gather, that you're trying to implement singleton pattern in Python.

Do subclass inherit attributes?

A subclass “inherits” all the attributes (methods, etc) of the parent class. This means that a subclass will have everything that its “parents” have. You can then change (“override”) some or all of the attributes to change the behavior. You can also add new attributes to extend the behavior.

How will you define subclasses in Python?

A class which inherits from a superclass is called a subclass, also called heir class or child class.


1 Answers

Sounds like you want the Factory Pattern. You define a factory method (either in your module, or perhaps in a common parent class for all the objects it can produce) that you pass the parameter to, and it will return an instance of the correct class. In python the problem is a bit simpler than perhaps some of the details on the wikipedia article as your types are dynamic.

class Animal(object):

    @staticmethod
    def get_animal_which_makes_noise(noise):
        if noise == 'meow':
            return Cat()
        elif noise == 'woof':
            return Dog()

class Cat(Animal):
    ...

class Dog(Animal):
    ...
like image 93
actionshrimp Avatar answered Sep 23 '22 23:09

actionshrimp