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

2024-04-19 08:24:22 发布

您现在位置: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()块中? 我哪里做错了?怎样才能用更简单的方法来做呢? (实际上我有一个json文件,不必为“xyz”操心太多)


Tags: nameinselfidjsonmaindefjohn
1条回答
网友
1楼 · 发布于 2024-04-19 08:24:22

Python2.*和Python3*之间此程序的行为不同。你知道吗

1.)xyz.keys()在Python2.7中给出了一个list,但需要从dict_keys类转换为Python3.6中的list。你知道吗

2.exec的行为在Python2.*和Python3.*See here之间有所不同。因此,如果您使用Python3运行程序,johntom尚未定义,在尝试访问它们时会出现错误。你知道吗

相关问题 更多 >