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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值