【问题标题】:Adding dynamic attribute to python class fails向 python 类添加动态属性失败
【发布时间】:2022-01-17 00:01:52
【问题描述】:

我正在尝试从javalang 向某个类动态添加属性:

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)

【问题讨论】:

    标签: python dynamic attributes


    【解决方案1】:

    显然,我的属性一直都在那里,只是没有打印出来,因为 __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
    

    显式添加我的属性,我现在可以打印我的类(向右滚动查看)

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多