简体   繁体   English

根据传递给外部函数的参数调用内部函数

[英]Call inner function based on the argument passed to outer function

I have a function with one argument, and inside the function, there are inner functions with possible arguments which can be passed to the outer function. 我有一个带有一个参数的函数,并且在函数内部,有带有可能的参数的内部函数可以传递给外部函数。

def delete_alphabet(del_apha):
    def del_a():
        # code to delete a
    def del_b():
        # code to delete b
    def del_c():
        # code to delete c
    def del_d():
        # code to delete d

I want to call functions del_b() , del_c() , del_d() when I pass a to delete_alphabet(a) , call functions del_a() , del_c() , del_d() when I pass b to delete_alphabet(b) , call functions del_a() , del_b() , del_d() when I pass c to delete_alphabet(c) , call functions del_a() , del_b() , del_c() when I pass d to delete_alphabet(d) 我想调用函数del_b() del_c() del_d()当我通过adelete_alphabet(a) ,通话功能del_a() del_c() del_d()当我通过bdelete_alphabet(b)呼叫功能del_a() del_b() del_d()当我通过cdelete_alphabet(c) ,呼叫功能del_a() del_b() del_c()当我通过ddelete_alphabet(d)

Can someone suggest me a way to resolve this? 有人可以建议我解决此问题的方法吗?

In Python, functions are just objects. 在Python中,函数只是对象。 Your approach can be as straightforward as this: 您的方法可以很简单:

In [22]: def del_a(): print('deleting a')

In [23]: def del_b(): print('deleting b')

In [24]: def del_c(): print('deleting c')

In [25]: def del_d(): print('deleting d')

In [26]: funcs = {'a':(del_a, del_c, del_d), 'b': (del_a, del_b, del_d)}

In [27]: def delete_alphabet(del_alpha, funcs=funcs):
    ...:     for f in funcs[del_alpha]:
    ...:         f()
    ...:

In [28]: delete_alphabet('a')
deleting a
deleting c
deleting d

In [29]: delete_alphabet('b')
deleting a
deleting b
deleting d

EDIT So, given the clarifications in the comments, my approach would be the following: 编辑因此,鉴于评论中的澄清,我的方法如下:

In [30]: funcs = [('a', del_a), ('b', del_b), ('c', del_c), ('d', del_d)]

In [31]: def delete_alphabet(del_alpha, funcs=funcs):
    ...:     for c, f in funcs:
    ...:         if c != del_alpha:
    ...:             f()
    ...:

In [32]: delete_alphabet('a')
deleting b
deleting c
deleting d

In [33]: delete_alphabet('b')
deleting a
deleting c
deleting d

In [34]: delete_alphabet('c')
deleting a
deleting b
deleting d

In [35]: delete_alphabet('d')
deleting a
deleting b
deleting c

It is much cleaner to keep some sort of mapping from string to function rather than using some eval hack. 保留从字符串到函数的某种映射比使用一些eval方法要干净得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM