gpt4 book ai didi

python - 我怎样才能清理 exec 的使用,无法让 setattr 来完成这项工作?

转载 作者:太空宇宙 更新时间:2023-11-03 19:07:08 26 4
gpt4 key购买 nike

我想检查以文本表示的任意(在数据中定义)规则集,而 eval() 可以很好地完成这项工作。

例如定义一个规则来检查 A 和 B 是否都有效:

Rule = "A and B"
print eval(Rule)

那么如何动态地将值分配给任意一组项目?

我有一个命名选项列表和一个选择列表。选择中的所有内容都被视为有效 (True),选项中但不在选择中的所有内容都被视为无效 (False)。

所以这段代码可以工作,但我不喜欢它,因为我在本地 namespace 内设置值,并且无法防止选项名称与本地变量发生冲突。

def CheckConstraints(self, Selections):
'Validate the stored constraints'
Good = True
## Undefined options default to False
for i in self.Options:
exec(i+" = False") ## Bad - can I use setattr?
## Set defined Options to True
for i in Selections:
exec(i+" = True") ## Bad - can I use setattr?
for i in self.Constraints:
if not eval( i ):
Good = False
print "Constraint Check Failure:", i, Selections
else:
print "Constraint Check OK:", i, Selections
return Good

我尝试过使用setattr,但不清楚setattr正在设置什么,并且eval似乎无法使用设置的值。

我使用的是 python 2.7x

有什么建议欢迎吗?

最佳答案

eval 可以将字典作为包含新环境的第二个参数。创建一个字典 env 并在其中设置新变量,这确保它不会与您的本地命名空间发生冲突:

def CheckConstraints(self, Selections):
'Validate the stored constraints'
Good = True
env = {}
## Undefined options default to False
for i in self.Options:
env[i] = False
## Set defined Options to True
for i in Selections:
env[i] = True
for i in self.Constraints:
if not eval(i, env):
Good = False
print "Constraint Check Failure:", i, Selections
else:
print "Constraint Check OK:", i, Selections
return Good

关于python - 我怎样才能清理 exec 的使用,无法让 setattr 来完成这项工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425831/

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