# 工厂类方法1,这些类的实例方法名 相同
class Fruit(object):
def __init__(self):
pass
def print_color(self):
pass
# 工厂类方法2
class Apple(Fruit):
def __init__(self):
pass
def print_color(self):
print("apple is in red")
# 工厂类方法3
class Orange(Fruit):
def __init__(self):
pass
def print_color(self):
print("orange is in orange")
# 管理类
class FruitFactory(object):
fruits = {"apple": Apple, "orange": Orange}
def __new__(cls, name):
if name in cls.fruits.keys():
return cls.fruits[name]()
else:
return Fruit()
fruit1 = FruitFactory("apple")
fruit2 = FruitFactory("orange")
fruit1.print_color() # 输出: apple is in red
fruit2.print_color() # 输出: orange is in orange
标签:__,python,self,工厂,orange,color,print,方法,def
From: https://www.cnblogs.com/lanjianhua/p/18460839