Animal is the parent class, Dog and Cat inherit the parent class, and then create a factory class, to set the match rules by the static method,
the same examples of the way and call mode, depending on the content of the incoming, the results are different.
class Animal:
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
def getName(self):
return "dog"
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
def getName(self):
return "cat"
class AnimailMake:
@staticmethod
def makeanimial(name):
am = None
if name == "cat":
am = Cat(name)
elif name == "dog":
am = Dog(name)
else:
am = Animal(name)
return am
if __name__ == '__main__':
am = AnimailMake.makeanimial("cat")
print(am.getName())
am = AnimailMake.makeanimial("dog")
print(am.getName())
am = AnimailMake.makeanimial("?")
print(am.getName())