zoukankan      html  css  js  c++  java
  • 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]

  • 相关阅读:
    MySql学习
    python学习笔记
    关于字符编码的理解
    session与cookie
    常用的表单元素
    Linq基础
    发送邮件。。
    进程与线程
    winform知识点集合
    winform基础与简单的窗体
  • 原文地址:https://www.cnblogs.com/linyihai/p/6239140.html
Copyright © 2011-2022 走看看