如何返回匹配子类的对象?

2024-10-01 00:25:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个方法,根据一些输入数据返回一个子类的对象。我来解释一下

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

我不知道如何用恰当的方式写这个。有什么建议吗?当然这是个狗屁的例子。我想把这个应用到某种通信协议的不同包上。你知道吗

如果我用一种完全错误的方式来处理这个问题,请告诉我:)


Tags: datareturnifparsedefpassallclass
1条回答
网友
1楼 · 发布于 2024-10-01 00:25:34

为什么不传递确切的类名,在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')

相关问题 更多 >