我正在尝试编写一个方法,根据一些输入数据返回一个子类的对象。我来解释一下
class Pet():
@classmethod
def parse(cls,data):
#return Pet() if all else fails
pass
class BigPet(Pet):
size = "big"
@classmethod
def parse(cls,data):
#return BigPet() if all subclass parsers fails
pass
class SmallPet(Pet):
size = "small"
@classmethod
def parse(cls,data):
#return SmallPet() if all subclass parsers fails
pass
class Cat(SmallPet):
sound = "maw"
@classmethod
def parse(cls,data):
#return Cat() if all criteria met
pass
class Dog(BigPet):
sound = "woof"
@classmethod
def parse(cls,data):
#return Dog() if all criteria met
pass
假设我想做一个“解析器”,比如:
Pet.parse(["big", "woof"])
> returns object of class Dog
Pet.parse(["small", "maw"])
> returns object of class Cat
Pet.parse(["small", "blup"])
> returns object of class SmallPet
我不知道如何用恰当的方式写这个。有什么建议吗?当然这是个狗屁的例子。我想把这个应用到某种通信协议的不同包上。你知道吗
如果我用一种完全错误的方式来处理这个问题,请告诉我:)
为什么不传递确切的类名,在
globals()
中查找并实例化它呢?你知道吗相关问题 更多 >
编程相关推荐