简体   繁体   中英

Can you call/use a function returned from a list in Python?

I'm trying to store a function in a list, retrieve the function from the list later, and then call on that function. This is basically what I want to do, without any specifics. It doesn't show my purpose, but it's the same issue.

elements: list = [] # List meant to contain a tuple with the name of the item and the function of the item.
def quit_code():
    exit()
element.append(("quit", quit_code))

Now, somewhere else in the code, I want to be able to use an if statement to check the name of the item and, if it's the right one at that time, run the function.

user_input = "quit" # For brevity, I'm just writing this. Let's just imagine the user actually typed this.
if elements[0][0] == user_input:
    #This is the part I don't understand so I'm just going to make up some syntax.
    run_method(elements[0][1])

The method run_method that I arbitrarily made is the issue. I need a way to run the method returned by elements[0][1], which is the quit_code method. I don't need an alternative solution to this example because I just made it up to display what I want to do. If I have a function or object that contains a function, how can I run that function.

(In the most simplified way I can word it) If I have object_a (for me it's a tuple) that contains str_1 and fun_b, how can I run fun_b from the object.

To expand on this a little more, the reason I can't just directly call the function is because in my program, the function gets put into the tuple via user input and is created locally and then stored in the tuple.

__list_of_stuff: list = []    
def add_to_list(name, function):
    __list_of_stuff.append((name, function))

And then somewhere else

def example_init_method():
    def stop_code():
        exit()

    add_to_list("QUIT", stop_code())

Now notice that I can't access the stop_code method anywhere else in the code unless I use it through the __list_of_stuff object.

Finally, It would be nice to not have to make a function for the input. By this, I mean directly inserting code into the parameter without creating a local function like stop_code. I don't know how to do this though.

Python treats functions as first-class citizens. As such, you can do things like:

def some_function():
    # do something
    pass

x = some_function

x()

Since you are storing functions and binding each function with a word (key), the best approach would be a dictionary. Your example could be like this:

def quit_code():
    exit()

operations = dict(quit=quit_code)

operations['quit']()

A dictionary relates a value with a key. The only rule is the key must be immutable. That means numbers, strings, tuples and other immutable objects.

To create a dictionary, you can use { and }. And to get a value by its key, use [ and ]:

 my_dictionary = { 'a' : 1, 'b' : 10 }

 print(my_dictionary['a'])    # It will print 1

You can also create a dictionary with dict , like so:

 my_dictionary = dict(a=1, b=10)

However this only works for string keys.

But considering you are using quit_code to encapsulate the exit call, why not using exit directly?

 operations = dict(quit=exit)

 operations['quit']()

If dictionaries aren't an option, you could still use lists and tuples:

 operations = [('quit',exit)]

 for key, fun in operations:
     if key == 'quit':
         fun()

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