如何返回匹配子类的对象



我试图写一个方法,应该返回一个子类的对象取决于一些输入数据。让我试着解释

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()中查找并实例化它?

def parse_pet(class_name, data):
    # will raise a KeyError exception if class_name doesn't exist
    cls = globals()[class_name]
    return cls(data)
cat = parse_pet('Cat', 'meow')
big_pet = parse_pet('BigPet', 'woof')

最新更新