根据传递给外部函数

时间:2017-03-01 19:23:58

标签: python

我有一个带有一个参数的函数,在函数内部,有一些带有可能参数的内部函数,可以传递给外部函数。

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

当我将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) <img src="http://example.com/wp-content/themes/themename/hp-image.jpg"/>

有人可以建议我解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:0)

在Python中,函数只是对象。您的方法可以像这样简单:

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

修改 因此,鉴于评论中的澄清,我的方法如下:

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

从字符串到函数保持某种映射比使用某些eval hack更清晰。