首页 > python > 封装决定初始化哪个子类

封装决定初始化哪个子类 (Encapsulate the decision which child class to initialize)

问题

我有一个父类和不同的子类。我想封装在初始化中初始化子类的决定。一个简单的例子:

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):
        ...

这个简单的例子将以递归方式结束并且不起作用,但是它用于说明我的问题:如何在父类的初始化中封装决定哪个子类初始化?或者这完全是一个愚蠢的想法?

解决方法

虽然用例不是很清楚,但我会使用工厂设计模式来实现类似的功能。一个基本的例子可以是:

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')

工厂方法设计模式的另一个例子

问题

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?

解决方法

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

相似信息