python 中的循环外未定义对象
Object is not being defined outside the loop in python
import json
xyz={"john": """{"name": "john","id":"123"}""","tom" : """{"name":"tom","id":"456"}"""}
class abc(object):
def __init__ (self,**d):
self.name=d['name'];
self.id=d['id'];
def main():
ks=xyz.keys()
for j in ks:
lm1="xyz['%s']" %(j)
ds=eval(lm1);
ds1=json.loads(ds)
ln="%s=abc(**ds1)" %(j)
print(ln)
exec(ln);
ln2="%s.name" %(j)
print(eval(ln2));
print(john.name)
print(tom.id)
if __name__ == "__main__":
main();
错误是
tom=abc(**ds1)
tom
john=abc(**ds1)
john
Traceback (most recent call last):
File "new6.py", line 26, in <module>
main();
File "new6.py", line 22, in main
print(john.name)
NameError: name 'john' is not defined
为什么我无法访问 main() 块中的 "tom.name"、"john.name"?
我哪里做错了?以及如何以更简单的方式完成?
(我实际上有一个 json 文件,不用太在意 "xyz")
此程序的行为在 Python2.* 和 Python3*.
之间是不同的
1.) xyz.keys()
在 Python2.7 中给出 list
,但需要从 dict_keys
class 转换为 list
在 Python3.6。
2.) exec
的行为在 Python2.* 和 Python3.* 之间有所不同 See here 了解更多详情。因此,如果你是 运行 你的程序 Python3,john
和 tom
还没有被定义,当你试图访问它们时你会得到一个错误。
import json
xyz={"john": """{"name": "john","id":"123"}""","tom" : """{"name":"tom","id":"456"}"""}
class abc(object):
def __init__ (self,**d):
self.name=d['name'];
self.id=d['id'];
def main():
ks=xyz.keys()
for j in ks:
lm1="xyz['%s']" %(j)
ds=eval(lm1);
ds1=json.loads(ds)
ln="%s=abc(**ds1)" %(j)
print(ln)
exec(ln);
ln2="%s.name" %(j)
print(eval(ln2));
print(john.name)
print(tom.id)
if __name__ == "__main__":
main();
错误是
tom=abc(**ds1)
tom
john=abc(**ds1)
john
Traceback (most recent call last):
File "new6.py", line 26, in <module>
main();
File "new6.py", line 22, in main
print(john.name)
NameError: name 'john' is not defined
为什么我无法访问 main() 块中的 "tom.name"、"john.name"? 我哪里做错了?以及如何以更简单的方式完成? (我实际上有一个 json 文件,不用太在意 "xyz")
此程序的行为在 Python2.* 和 Python3*.
之间是不同的1.) xyz.keys()
在 Python2.7 中给出 list
,但需要从 dict_keys
class 转换为 list
在 Python3.6。
2.) exec
的行为在 Python2.* 和 Python3.* 之间有所不同 See here 了解更多详情。因此,如果你是 运行 你的程序 Python3,john
和 tom
还没有被定义,当你试图访问它们时你会得到一个错误。