python 使用字符串名调用类以及调用类方法名

在python中,有时调用者仅知道类名和类方法,不负责实际的函数调用,而是将要调用的类名和类方法告诉一个中间函数,由中间函数负责实际调用函数。中间函数需以被告知的字符串调用类和类方法。                                                                               在万物皆对象,我们需要将传进来的字符串转化为类对象,这里我们可以使用eval实现。而以字符串形式调用类方法,可以使用内置方法getattr实现,以下是详细例子。

class SayHello():
    def say(self):
        print 'hello'

if __name__ == '__main__':
    # normal call class method
    i_s_h = SayHello()
    i_s_h.say()
    # use string call class method
    c_str = eval('SayHello')()
    print c_str
    c_str.say()
    # direct use class method
    getattr(c_str,'say')()

以上输出:

hello
<__main__.SayHello instance at 0x0000000002242848>
hello
hello
[Finished in 0.3s]

原文地址:https://www.cnblogs.com/linyihai/p/6239140.html