字符串调用函数

标准库operator中methodcaller方法

#!/usr/bin/python
# -*- coding: utf-8 -*-
from operator import methodcaller


class Test(object):
    @staticmethod
    def fun():
        print u"调用了..."


c = Test()
print methodcaller("fun")(c)

#调用了...
#None

 

methodcaller方法是直接执行对象c中的fun函数

返回值是None

 

getattr()

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


class Test(object):
    @staticmethod
    def fun():
        print u"调用了..."


c = Test()
f = getattr(c, 'fun')
print f 
f()

#<function fun at 0x00000000027D8C88>
#调用了...

getattr()方法相当于将对象c中的fun函数地址赋值给f

返回值是一个地址

 

locals(),globals()和eval()也可以实现,这里就不一一叙述

posted @ 2019-05-11 10:47  LuoSpider  阅读(1010)  评论(0编辑  收藏  举报