[Python] Dynamic function call (via function name)

Source: Internet
Author: User

2018-04-09 Update

Using the built-in function in Python eval () , function Description:

def # Real signature Unknown    """     Evaluate The given source in the context of globals and locals.        The source is a string representing a Python expression    or a code object as returned by compile ().    The globals must be a dictionary and locals can is any mapping, defaulting to the current    globals and locals.    If only globals are given, locals defaults to it.     """    Pass

Example 1:

deffunction2 (name, age):Print("Name:%s, age:%s"%(name, age))if __name__=='__main__': eval (  "function2") ("Alice", one by one) #or:args = ["Alice ", 11] Kwargs={} eval (  "function2") (*args, * *Kwargs) """The results are: Name:alice, age:11"""

Example 2:

classTest (object): States= [u"greater than or equal to zero", u"greater than or equal to two"] State2function= {u"greater than or equal to zero":"check_gt0", u"greater than or equal to two":"CHECK_GT2"}@staticmethoddefcheck_gt0 (x):returnX >=0 @staticmethoddefCHECK_GT2 (x):returnX >= 2defPredict (self, x): forStateinchtest.states: check_ans = eval ("Test." + test.state2function[state]) (x) #  Call a method in the Test class             Print(state, Test.state2function[state], X, Check_ans)if __name__=='__main__': Test=Test () test.predict (x=-1) test.predict (x=1) test.predict (x=2)    """output: greater than or equal to zero check_gt0-1 false greater than or equal to two check_gt2-1 false is greater than or equal to zero check_gt0 1 True is greater than or equal to two CHECK_GT2 1 False Greater than or equal to zero Check_gt0 2 true greater than or equal to two CHECK_GT2 2 true"""

*************************************************************************************************************** **********************************************

2017-08-09

The corresponding function is obtained by the string function name

The use of functions as parameters is more intuitive:

def func (A, b):     return A + bdef  Test (F, A, B):        print3, 5)

However, in some cases, the question of which function to pass is not predetermined, for example, the function name is related to a variable. You can use func = Globals (). Get (Func_name) to get the function:

defFunc_year (s):Print 'func_year:', SdefFunc_month (s):Print 'Func_month:', S STRs= [' Year','Month'] forSinchstrs:globals (). Get ('func_%s'%s) (s)"""Output: Func_year:yearfunc_month:month"""

[Python] Dynamic function call (via function name)

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.