您可以从使用 ast.dump 开始了解您正在处理的代码的 AST 结构:
import ast
code='self.x = 10'
print(ast.dump(ast.parse(code), indent=2))
这输出:
Module(
body=[
Assign(
targets=[
Attribute(
value=Name(id='self', ctx=Load()),
attr='x',
ctx=Store())],
value=Constant(value=10))],
type_ignores=[])
从中你可以看到你想要寻找的是Assign节点,其中targets的第一个是Attribute节点,其value是Name节点,id是'self'和'x' 中的一个 attr。
有了这些知识,你就可以使用ast.walk遍历AST节点来寻找具有上述属性的节点,将其value修改为Constant节点,value为20,最后使用ast.unparse 将 AST 转换回一串代码:
import ast
code = '''
import sys #Just any module
class SomeClass:
def __init__(self):
self.x = 10
self.b = 15
def a_func(self):
print(self.x)
'''
tree = ast.parse(code)
for node in ast.walk(tree):
if (
isinstance(node, ast.Assign) and
isinstance((target := node.targets[0]), ast.Attribute) and
isinstance(target.value, ast.Name) and
target.value.id == 'self' and
target.attr == 'x'
):
node.value = ast.Constant(value=20)
print(ast.unparse(tree))
这输出:
class SomeClass:
def __init__(self):
self.x = 20
self.b = 15
def a_func(self):
print(self.x)
请注意,ast.unparse 需要 Python 3.10 或更高版本。如果您使用的是早期版本,则可以改用 astunparse package 中的 astunparse.unparse。
演示:https://trinket.io/python3/3b09901326