gpt4 book ai didi

python - 为什么不能将 eval() 函数与私有(private)变量一起使用?

转载 作者:行者123 更新时间:2023-12-04 14:46:22 25 4
gpt4 key购买 nike

我想知道为什么不能对私有(private)属性使用 eval() 函数。

class A:
def __init__(self):
__private = 5
print(__private + 2) # Prints '7'
print(eval('__private + 2')) # NameError: name '__private' is not defined

A()

最佳答案

这与名称修改有关,请参阅 documentation :

Notice that code passed to exec() or eval() does not consider theclassname of the invoking class to be the current class; this issimilar to the effect of the global statement, the effect of which islikewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.

因此,要在 eval() 中正确使用私有(private)变量,它必须以经过修饰的形式传递,例如print(eval('_A__private + 2'))

关于python - 为什么不能将 eval() 函数与私有(private)变量一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69975345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com