Python invokes the class with a string name and invokes the class method name

Source: Internet
Author: User

In Python, sometimes the caller knows only the class name and the class method, not the actual function call, but the class name and class method that will be called to tell an intermediate function, which is responsible for the actual call of the function by the intermediate function.                                                                               The intermediate function calls the class and class methods in the known string. In all things, we need to convert the incoming string into a class object, where we can use eval to implement it. Instead of invoking the class method as a string, you can use the built-in method GetAttr implementation, here is a detailed example.

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 ') ()

Above output:

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

Python invokes the class with a string name and invokes the class method name

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.