I'm trying to write a method that is supposed to return me an object of a subclass depending on some input data. Let me try to explain
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
Imagine that I would like to make a "parser", such as this:
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
I have no idea of how to write this in a proper way. Any suggestions? Of course this is a bullshit example. I'd like to apply this on different packets of a communication protocol of some kind.
If i am approaching this in a completely wrong way, please tell me :)
Aucun commentaire:
Enregistrer un commentaire