Using a dictionary to select function to execute

前端 未结 10 1989
走了就别回头了
走了就别回头了 2020-11-27 13:05

I am trying to use functional programming to create a dictionary containing a key and a function to execute:

myDict={}
myItems=(\"P1\",\"P2\",\"P3\",....\"         


        
相关标签:
10条回答
  • 2020-11-27 14:01

    You can just use

    myDict = {
        "P1": (lambda x: function1()),
        "P2": (lambda x: function2()),
        ...,
        "Pn": (lambda x: functionn())}
    myItems = ["P1", "P2", ..., "Pn"]
    
    for item in myItems:
        myDict[item]()
    
    0 讨论(0)
  • 2020-11-27 14:07

    You are wasting your time:

    1. You are about to write a lot of useless code and introduce new bugs.
    2. To execute the function, your user will need to know the P1 name anyway.
    3. Etc., etc., etc.

    Just put all your functions in the .py file:

    # my_module.py
    
    def f1():
        pass
    
    def f2():
        pass
    
    def f3():
        pass
    

    And use them like this:

    import my_module
    
    my_module.f1()
    my_module.f2()
    my_module.f3()
    

    or:

    from my_module import f1
    from my_module import f2
    from my_module import f3
    
    f1()
    f2()
    f3()
    

    This should be enough for starters.

    0 讨论(0)
  • 2020-11-27 14:08

    Simplify, simplify, simplify + DRY:

    tasks = {}
    task = lambda f: tasks.setdefault(f.__name__, f)
    
    @task
    def p1():
        whatever
    
    @task
    def p2():
        whatever
    
    def my_main(key):
        tasks[key]()
    
    0 讨论(0)
  • 2020-11-27 14:08
    def p1( ):
        print("in p1")
    
    def p2():
        print("in p2")
    
    myDict={
        "P1": p1,
        "P2": p2
    
    }
    
    name=input("enter P1 or P2")
    

    myDictname

    0 讨论(0)
提交回复
热议问题