好...代码先。
def magic(node):
spells_dict = {"AR_OP":ar_op_magic, "PRE_OP":pre_op_magic}
if node:
if node.text in spells_dict:
return spells_dict[node.text](node)
else:
return magic(node.l) + magic(node.r)
else:
return ""
在递归电话期间,将创建大量的spells_dict副本。我知道我可以使这个dict Global做到,但是我不想要,因为这仅与魔术功能有关。因此,我可以创建一些类,并将Spells_dict和功能放在其中,但看起来并不是一个不错的解决方案。
有什么办法只用一个spells_dict的副本来做到这一点?
我看不到MAGIC_SPELLS
常数的任何问题。您可以在magic
函数附近进行本地环境,因此您知道,属于属性:
def magic_default(node):
return magic(node.l) + magic(node.r)
MAGIC_SPELLS = {
'AR_OP': ar_op_magic,
'PRE_OP': pre_op_magic,
}
def magic(node):
if node:
func = MAGIC_SPELLS.get(node.text, magic_default)
return func(node)
return ""