【发布时间】:2019-03-24 02:35:37
【问题描述】:
我希望能够基于枚举类创建对象,并使用字典。像这样的:
class IngredientType(Enum):
SPAM = auto() # Some spam
BAKE_BEANS = auto() # Baked beans
EGG = auto() # Fried egg
class Ingredient(object):
pass
class Spam(Ingredient):
pass
class BakedBeans(Ingredient):
pass
class Egg(Ingredient):
pass
class IngredientFactory(object):
"""Factory makes ingredients"""
choice = {
IngredientType.SPAM: IngredientFactory.MakeSpam,
IngredientType.BAKED_BEANS: IngredientFactory.MakeBakedBeans,
IngredientType.EGG: IngredientFactory.MakeEgg
}
@staticmethod
def make(type):
method = choice[type]
return method()
@staticmethod
def makeSpam():
return Spam()
@staticmethod
def makeBakedBeans():
return BakedBeans()
@staticmethod
def makeEgg():
return Egg()
但我得到了错误:
NameError: name 'IngredientFactory' is not defined
由于某种原因无法创建字典。 我哪里错了?
【问题讨论】:
-
你到底为什么要这样做?
-
在类解析/定义时,
IngredientFactory还不存在。直到 Python 解析器在IngredientFactory类定义下留下最后一个缩进,它才可供参考。 -
代码究竟在哪里引发了错误?
-
配料工厂的第 4 行它给了我错误。
-
这是做工厂的错误方法吗?
标签: python dictionary enums factory