网页、代码与不可信内容:练习答案
参考实现
将正文source追加以下文本后重新执行解析循环:
python
source += '\nasync def load():\n return "ok"\n'
tree = ast.parse(source)
names = [n.name for n in tree.body if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef))]
assert names == ['add','fail','load']类方法位于ClassDef.body,不在模块直接body中。可递归访问,但必须携带类名路径,否则不同类的同名方法会身份冲突。
返回题目。