对象未在python中的循环外部定义

对象未在python中的循环外部定义,python,class,object,encapsulation,Python,Class,Object,Encapsulation,错误是 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:

错误是

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)
汤姆
约翰=abc(**ds1)
厕所
回溯(最近一次呼叫最后一次):
文件“new6.py”,第26行,在
main();
文件“new6.py”,第22行,在main中
打印(john.name)
NameError:未定义名称“john”
为什么我不能访问main()块中的“tom.name”、“john.name”? 我哪里做错了?如何能以更简单的方式完成?
(我实际上有一个json文件,不用太在意“xyz”)

这个程序的行为在Python2.*和Python3*之间是不同的

1.
xyz.keys()
在Python2.7中提供了一个
列表
,但需要在Python3.6中从
dict_keys
类转换为
列表


2.
exec
的行为在Python2.*和Python3.*之间有所不同,以了解更多详细信息。因此,如果您使用Python3运行程序,
john
tom
尚未定义,您在尝试访问它们时会出错

@khelwood在提出问题时出错……这是我第一次看到这个程序运行良好。如果我运行它,没有名称错误。可能是因为,您可能正在python2中运行它。*,我希望它在3中运行*
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