eval function makes me sad

 Today, this first contact with the eval function, let me sad one. I took as a string concatenation, the result was wrong day far away. The following is the general situation in this code, it kept me newspaper NameError: name 'qinfeng' is not defined.

  class_obj = eval('qinfeng.zheng.ipvsadm.%s()' % class_name)

What was a ghost, I thought, this is a string concatenation Nyima, also need to be defined.

A handful of behind Baidu, found from a bit of melon.

After the original eval Sao operation, class_obj is an object instance, but at that time did not lead pack.

 

The following simulate what, to facilitate later review, remember it is really the heart of the dog.

 

1. The following code structure

 

 

 

2. ipvsadm.py

class the IPVS ():
     DEF say (Self):
         Print ( " I'm boring ... " )

 

3. Test class test.py

import qinfeng.zheng.ipvsadm

if __name__ == '__main__':
    class_name = 'Ipvs'
    class_obj = eval('qinfeng.zheng.ipvsadm.%s()' % class_name)
    print(type(class_obj))
    class_obj.say()

 

When the import qinfeng.zheng.ipvsadm commented, running test.py will report the following error

Traceback (most recent call last):
  File "E:/ws/python/20191106/qinfeng/zheng/test.py", line 5, in <module>
    class_obj = eval('qinfeng.zheng.ipvsadm.%s()' % class_name)
  File "<string>", line 1, in <module>
NameError: name 'qinfeng' is not defined

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/z-qinfeng/p/11809297.html