标准库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函数

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

返回值是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()也可以实现,这里就不一一叙述

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄