简体   繁体   中英

dictionary of functions returns every function

I am having difficulty returning a specific function from a dictionary of predefined functions. Here is my code:

import random

def bos1():
    print ("function 1")

def bos2():
    print ("function 2")

def bos3():
    print("function 3")

def bos4():
    print("function 4")
count = 0

while True :
    if count <4:

        bos = "bos"
        poz = random.randint(3, 4)
        bos = bos+str(poz)


        bosdict = {'bos1': bos1(),'bos2':bos2(),'bos3':bos3(),'bos4':bos4()}
        count += 1
        print("please only printe one",bosdict[bos])
        print("count:\n", count)

        input("")

    else:

        bos = "bos"
        poz = random.randint(1, 2)
        bos = bos+str(poz)


        bosdict = {'bos1': bos1(),'bos2':bos2(),'bos3':bos3(),'bos4':bos4()}
        count += 1
        print("please only printe one",bosdict['bos'])
        print("count:\n", count)

        input("")

I have created a successful version of this program that uses arithmetic functions. It will return the appropriate function relative to the string that has been concatenated upon each iteration. However with functions that are meant to return a string it returns all four functions in the dictionary on each iteration. Why is this happening and how can I make it behave the same as the arithmetic dictionary?

you're not creating a dictionary of function but a dictionary of function calls (which are None since your functions return nothing): all functions are executed when creating the dictionary.

Remove the () in your dict, you'll use it after retrieving the value in the dict to call the function:

bosdict = {'bos1': bos1,'bos2':bos2,'bos3':bos3,'bos4':bos4}

Call a random function like this:

bosdict[random.choice(list(bosdict.keys()))]()

or maybe simpler you don't need the keys in that case, only the values:

random.choice(list(bosdict.values()))()

or with the generated name from random index:

bosdict["bos{}".format(count)]()

note that dynamically calling the functions only has some interest if the functions are slow to compute or have a side-effect or parameters, else it's better to create a static dictionary (using return instead of print as Chris noted).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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