自动将对象从类转换为子类

丹尼尔

我必须关注以下问题。我有一个数据输入,其中定义了一个类型(在下面的示例中为动物)。基于此类型,我需要不同的子类,因为我希望基于类型具有不同的属性。这是一个例子:

class pet:
    def __init__(self, dict):
        self.name = dict['name']
        self.type = dict['type']


class dog(pet):
    def __init__(self, dict):
        pet.__init__(self, dict)
        self.weight = dict['weight']


class cat(pet):
    def __init__(self, dict):
        pet.__init__(self, dict)
        self.color = dict['color']


if __name__ == '__main__':
    pet1 = {'name': 'Harry', 'type': 'dog', 'weight': 100}
    pet2 = {'name': 'Sally', 'type': 'cat', 'color': 'blue'}

    mypet1 = pet(pet1)
    mypet2 = pet(pet2)

我想根据类型参数自动将宠物对象转换为狗或猫。最后一点很关键,因为会有很多宠物,而且我无法手工读取类型并显式使用相应的子类。有没有办法做到这一点?

提前致谢

暗影游侠

首先,不要只是绕过dicts;隐藏实际所需的参数,并丑化代码。对每个初始化器上识别的参数使用常规名称,将其余的作为捕获,**kwargs并将其传递给初始化器链。

其次,要实现您的目标,请将替代构造函数作为classmethodonPet并使用它。classmethod可以返回一个新对象,并且它们不限于对已创建的对象进行操作__init____new__可以进行替换__init__以实现类似的效果,但是更复杂,并且通常不太明显):

class pet:
    def __init__(self, name, type):
        self.name = name
        self.type = type

    @classmethod
    def fromtype(cls, type, **kwargs):
        for c in cls.__subclasses__():
            if c.__name__ == type:
                break
        else:
            raise ValueError("Unknown type: {!r}".format(type))
        return c(type=type, **kwargs)

class dog(pet):
    def __init__(self, weight, **kwargs):
        pet.__init__(self, **kwargs)
        self.weight = weight


class cat(pet):
    def __init__(self, color, **kwargs):
        pet.__init__(self, **kwargs)
        self.color = color

用法仅略有变化,从:

mypet1 = pet(pet1)
mypet2 = pet(pet2)

至:

mypet1 = pet.fromtype(**pet1)
mypet2 = pet.fromtype(**pet2)

当您需要直接构造对象时,可以将常规参数传递给常规构造函数,而不是构造dict本来没有使用的参数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章