在python循环外没有定义对象

时间:2017-10-12 12:19:06

标签: 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:
      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”)

1 个答案:

答案 0 :(得分:1)

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

1。)xyz.keys()在Python2.7中给出list,但是需要在Python3.6中从dict_keys类转换为list

2.。){2}的行为exec在Python2。*和Python3。* See here之间有所不同。因此,如果您使用Python3运行程序,则尚未定义johntom,并且在尝试访问它们时会出错。