我正在尝试减少代码中的复制/粘贴,但偶然发现了这个问题。我已经搜索了答案,但所有答案都使用类的实例作为键,我找不到使用类定义本身作为键的任何内容(我不知道是否可能)。
我的代码是这样的:
# All chunkFuncs keys are class definitions, all values are functions
chunkFuncs = {Math_EXP : Math_EXPChunk, Assignment : AssignmentChunk, Function : FunctionChunk}
def Chunker(chunk, localScope):
for chunkType in chunkFuncs:
if isinstance(chunk,chunkType):
# The next line is where the error is raised
localScope = chunkFuncs[chunk](chunk,localScope)
return localScope
错误是这个
TypeError: unhashable type: 'Assignment'
以下是类定义:
class Math_EXP(pyPeg.List):
grammar = [Number,Symbol],pyPeg.maybe_some(Math_OP,[Number,Symbol])
class Assignment(pyPeg.List):
grammar = Symbol,'=',[Math_EXP,Number]
class Function(pyPeg.List):
grammar = Symbol,'(',pyPeg.optional(pyPeg.csl([Symbol,Number])),')'
我可以使用其他方法来获得相同的效果吗?
谢谢。