我知道PythonDunder变量是什么,并且我知道名称mangling。
但是,由于某些原因,我无法在下面的代码片段中访问But变量:
for node in ast.find_all((Call,)):
# Check if the identifier match the extension name
if node.node.identifier == 'myapp.ext.MyExtension':
# I want to access node.__meta
print("==> type(node) = %s" % type(nod))
print("==> node.__dict__ = %s" % node.__dict__")其中的指纹:
==> type(node) = <class 'jinja2.nodes.Call'>
==> node.__dict__ = {
'kwargs': [],
# ... a bunch of other attributes
# The __meta attribute below is what I want to access
'__meta': {'type': 'checkbox', 'value': Const(value='checked'), 'name': Const(value='agree'), 'class': Const(value='bold')}
}由于node变量是Call类的一个实例,并且我希望访问它的__meta属性,根据名称mangling,我必须像这样做node._Call__meta,但是我得到了一个错误:
`'Call' object has no attribute '_Call__meta'`我做错了什么?
发布于 2019-10-29 11:04:16
您似乎对名称损坏和__dict__之间的交互方式略有误解。__dict__条目不受名称mangling的限制--如果您在__dict__中看到名称'__meta',那么该属性实际上是命名为__meta (而不是_Call__meta)。
你可以通过这个小小的演示来证实这一点:
class Demo:
__meta = 5
print('__meta' in vars(Demo)) # False
print('_Demo__meta' in vars(Demo)) # True有两种方法可以访问这个__meta属性:
如果您的代码不在类中,则可以使用
node.__dict__['__meta'].的__dict__中直接获取属性
https://stackoverflow.com/questions/58605984
复制相似问题