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