我正在尝试编写AST解释器/ REPL.ANTLRv4提供两个非常相似的接口(ParseTreeVisitor和ParseTreeListener)来遍历解析树.我似乎无法找到它们之间的任何重大差异,并且文档相当稀疏.一个界面比另一个更好吗?
我正在尝试创建一个行为类似于包装对象的包装类.到目前为止,我已经提出以下代码:
import functools
import types
method_wrapper = type((None).__str__)
class Box:
def __new__(cls, obj):
attrs = {}
attr_names = dir(obj)
for attr_name in attr_names:
attr = obj.__getattribute__(attr_name)
if isinstance(attr, (types.MethodType, method_wrapper)):
"Attr is a bound method, ignore self"
@functools.wraps(attr)
def wrapped_attr(self, *args, **kwargs):
return attr(*args, **kwargs)
attrs[attr_name] = wrapped_attr
elif isinstance(attr, types.FunctionType):
"attr is a static method"
attrs[attr_name] = staticmethod(attr)
else:
"attr is a property"
attrs[attr_name] = attr
cls = type(type(obj).__name__,
(cls, type(obj)),
attrs)
return object.__new__(cls)
Run Code Online (Sandbox Code Playgroud)
我试过测试它:
if __name__ == '__main__': …Run Code Online (Sandbox Code Playgroud)