将动态属性添加到 python class 失败

Adding dynamic attribute to python class fails

我正在尝试动态地向来自 javalang 的某些 class 添加属性:

In [1]: import javalang
In [2]: tree = javalang.parse.parse("class A { B c = ddd.doSomething(); }")
In [3]: print(tree.types[0].body[0].declarators[0].initializer)
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, selectors=[], type_arguments=None)

但是当我尝试简单地分配一个新属性时 (qualifier_type)

In [4]: tree.types[0].body[0].declarators[0].initializer.qualifier_type = "DDD"

没有任何反应:

In [5]: print(tree.types[0].body[0].declarators[0].initializer)
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, selectors=[], type_arguments=None)

显然,我的属性一直存在,只是没有打印出来,因为 __repr__ 实现迭代了 self.attrs

In [1]: import javalang
In [2]: tree = javalang.parse.parse("class A { B c = ddd.doSomething(); }")
In [3]: tree.types[0].body[0].declarators[0].initializer.qualifier_type = "DDD"
In [4]: print(tree.types[0].body[0].declarators[0].initializer.qualifier_type)
DDD

明确添加我的属性,我现在可以打印我的 class(向右滚动查看)

In [5]: tree.types[0].body[0].declarators[0].initializer.attrs += ("qualifier_type",)
In [6]: print(tree.types[0].body[0].declarators[0].initializer)
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, qualifier_type=DDD, selectors=[], type_arguments=None)