标准库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()也可以实现,这里就不一一叙述

相关文章:

  • 2021-08-06
  • 2022-12-23
  • 2021-07-09
  • 2021-08-15
  • 2022-12-23
  • 2021-12-12
  • 2021-08-09
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-16
  • 2021-09-02
  • 2021-12-12
  • 2022-12-23
相关资源
相似解决方案