要求:用指定的实例名调用函数

先想当然地写一下

cat vim my_exec.py 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys

class PersonComputer():
    def __init__(self,name):
        self.name = name

    def say_hi(self):
        print "Hellow,this is {}!".format(self.name)


if __name__ == '__main__':
    x1 = PersonComputer('host1')
    x2 = PersonComputer('host2')

    sys.argv[1].say_hi()

本意是调用脚本的时候带上x1或者x2,这样就能打印对应的host名字,结果报错

$ python my_exec.py x1
Traceback (most recent call last):
  File "my_exec.py", line 18, in <module>
    sys.argv[1].say_hi()
AttributeError: 'str' object has no attribute 'say_hi'

这样传入的字符,当然不会被当成是实例了,也就无法调用类定义的函数。
这个时候exec()就要出马了

$ cat my_exec.py 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys

class PersonComputer():
    def __init__(self,name):
        self.name = name

    def say_hi(self):
        print "Hellow,this is {}!".format(self.name)


if __name__ == '__main__':
    x1 = PersonComputer('host1')
    x2 = PersonComputer('host2')

    exec("{}.say_hi()".format(sys.argv[1]))

执行一下

$ python my_exec.py x1
Hellow,this is host1!
$ python my_exec.py x2
Hellow,this is host2!
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐