Vaughn Cato 指出,可以直接分配到locals()[object_type] = factory(object_type)
. 但是Python 文档禁止这样做:“注意:不应修改此字典的内容;更改可能不会影响解释器使用的局部变量和自由变量的值”
D. Shawley 指出,使用dict()
条目将保存函数的对象会更明智。create['cat']()
在解析器中使用会很简单。虽然这很引人注目,但我不喜欢括号和刻度所需的语法开销。
JF Sebastian 指着类。这就是我最终得到的结果:
# Omitting code of these classes for clarity
class Entity:
def __init__(file_name, line_number):
# Store location, good for debug, messages, and general indexing
# The following classes are the real objects to be generated by a parser
# Their constructors must consume whatever data is provided by the tokens
# as well as calling super() to forward the file_name,line_number info.
class Cat(Entity): pass
class Camel(Entity): pass
class Parser:
def parse_file(self, fn):
# ...
# Function factory to wrap object constructor calls
def create_factory(obj_type):
def creator(text, line_number, token):
try:
return obj_type(*token,
file_name=fn, line_number=line_number)
except Exception as e:
# For debug of constructor during development
print(e)
return creator
# Helper class, serving as a 'dictionary' of obj construction functions
class create: pass
for obj_type in (Cat, Camel):
setattr(create,
obj_type.__name__.lower(),
create_factory(obj_type))
# Parsing code now can use (again simplified for clarity):
expression = Keyword('cat').setParseAction(create.cat)
这是用于部署pyparsing 解析器的帮助代码。D. Shawley 是正确的,因为 dict 实际上更容易允许动态生成解析器语法。