Python Dynamic Call function

Source: Internet
Author: User

1. Dynamically invoke methods within a Python file based on string name eval ("Function_name") (parameter)

2. Dynamic invocation of a static method in a class based on a string, GetAttr (ClassName, "function_name") (parameter)

3. Apply (Functoin_name,parameters) This function_name is not a string, but a function object itself; Parameters is a parameter, similar (a, B,...) Such a format

4. When the function is unsure of the number of arguments, take a * or two * * their usage is fastidious. http://blog.csdn.net/feisan/article/details/1729905

The following example defines a dictionary of function lists, a dictionary that holds parameters for function objects and functions, which can be used to dynamically add functions to the dictionary, and finally execute

From collections import Ordereddictclass componentcheck:def __init__ (self, data_dir): Self.data_dir = Data_dir Self._extend_function_dic = Ordereddict ({}) def add_extend_function (self, function_name, *parameters): SE Lf._extend_function_dic[function_name] = Parameters def _check_extend_function (self): for function_name, Paramet ERs in Self._extend_function_dic.iteritems (): If not apply (function_name, parameters): Return Fa LSE return TRUECLASS Checkfunctions:def __init__ (self): Pass def Tollcost_check (Data_path): To Ll_cost_path = Os.path.join (Data_path, importer.dt_kor_toll_cost) tollcost_component = Componentcheck (toll_cost_pat h) tollcost_component.add_extend_function (Tollcost_component.check_file_pattern_list_match, CheckFunctions.TOLL_ Cost_filename_pattern) return Tollcost_component@staticmethod def speed_camera_check (data_path): Speed_ca Mera_path = Os.path.join (daTa_path, Importer.dt_safety_camera) speed_camera_component = Componentcheck (Speed_camera_path) Speed_camera_ Component.add_extend_function (speed_camera_component.check_not_exist_empty_directory) return Speed_camera_ Component

  

Python Dynamic Call function

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.