Egirus Ornila
Egirus Ornila

Reputation: 1314

Encapsulate the decision which child class to initialize

I have a parent class and different child classes. I want to encapsulate the decision which child class is to initialize in the initialization. A simple example:

class Person:
    def __init__(self, name):
        if self.name_is_male(name):
            real_instance = Male(name)
        else:
            real_instance = Female(name)
        return real_instance

    def name_is_male(self, name):
        if name == 'Donald':
            return True
        elif name == 'Daisy':
            return False
        else:
            raise ValueError('unknown name!')

class Male(Person):
    def __init__(self, name):
        ...

class Female(Person):
    def __init__(self, name):
        ...

This simple example will end in a recursion and doesn’t work, but it’s for illustrating my question: how to encapsulate the decision which child class to initialize in the initialization of a parent class? Or is this altogether a stupid idea?

Upvotes: 0

Views: 51

Answers (2)

Ankit Jaiswal
Ankit Jaiswal

Reputation: 23437

Though the use case is not very clear, I would have used factory design pattern to achieve something similar to this. A basic example can be:

class Person(object):
    # Create objects based on some name:

    @staticmethod
    def factory(name):
        if name== "Male": 
            return Male()
        elif name== "Female": 
            return Female()
        else:
            return None

class Male(Person):
    pass

class Female(Person):
    pass


person = Person.factory('Male')

Another example on factory method design pattern

Upvotes: 2

mklucz
mklucz

Reputation: 150

__init__ is not supposed to return anything (or rather: it has to return None). Imo it's not the best way of writing it, or as you put it "altogether a stupid idea". Is there a particular reason why it can't be an attribute?

Upvotes: 0

Related Questions