How to use a variable as function name in Python

前端 未结 6 1939
庸人自扰
庸人自扰 2020-12-01 16:17

Would it be possible to use a variable as a function name in python? For example:

list = [one, two, three]
for item in list:
    def item():
         some_st         


        
6条回答
  •  生来不讨喜
    2020-12-01 16:57

    Functions in Python are objects that have a name referencing them, so you can pass them around, store in lists and dictionaries (common use when creating jump-tables).

    I.e. this works:

       def one():
            print "1"
    
        def two():
            print "2"
    
        def three():
            print "3"
    
        l = [one, two, three]
    
        for item in l:
            item()
    

    Will print:

    1
    2
    3
    

    Don't use list as variable name, because this way you redefine buildin.

    def is the statement that is also executed, unlike function defenitions in compiled languages. So when you call def item(): you don't define function for one, two, three, but redefine item name.

    In general it is not quite clear what you're trying to do, but it doesn't look like a good idea. May be explain what you try to accomplish, or rethink the way you want to do it.

提交回复
热议问题