我想从字符串构造类,例如"red apple"
. 这将创建 class 的一个实例Apple
,它是 的子类Fruit
。问题是,color
属性应该属于Fruit
,而不是Apple
。因此,在我看来,创建对象的自然方式是:
- 解析字符串
- 创造
Fruit(color="red")
- 创造
Apple()
- 以某种方式使其成为一个单一的实体
到目前为止,我有 3 个选项:
一切都变成参数
class Fruit(object): def __init__(self, color): self.color = color def observe(self): print "Looks like a tasty %s fruit" % self.color @classmethod def fromstring(cls, string): color, kind = string.split() if kind == "apple": return Apple(color) class Apple(Fruit): def __init__(self, *args, **kwargs): super(Apple, self).__init__(*args, **kwargs) self.tasty = True def bite(self): print "I bite into a tasty apple" fruit = Fruit.fromstring("red apple")
color
属性是从外面填写的class Fruit(object): def observe(self): print "Looks like a tasty %s fruit" % self.color @classmethod def fromstring(cls, string): color, kind = string.split() if kind == "apple": ins = Apple() ins.color = color return ins class Apple(Fruit): def __init__(self): self.tasty = True def bite(self): print "I bite into a tasty apple" fruit = Fruit.fromstring("red apple")
最直接的方法:替换
__class__
class Fruit(object): def __init__(self, string): self.color, kind = string.split() if kind == "apple": self.__class__ = Apple Apple.__init__(self) def observe(self): print "Looks like a tasty %s fruit" % self.color class Apple(Fruit): def __init__(self): self.tasty = True def bite(self): print "I bite into a tasty apple" fruit = Fruit("red apple")
跑步
fruit.observe()
fruit.bite()
print type(fruit), fruit.tasty
给出相同的输出:
Looks like a tasty red fruit
I bite into a tasty apple
<class '__main__.Apple'> True
第一种方法可以说是最通用的,它需要传递参数,例如color
,在第三种方法中处理得更加优雅。然而,改变__class__
声音就像使用高级工具完成平凡的任务一样。有没有更好的方法来实现目标,或者我最好使用其中一种方法?
更新:我可能必须指出,在现实生活中Fruit
' 和Apple
' 的初始化程序应该设置的属性数量是可变的,总共大约 15 个。