1

Is it possible to store a certain function as a variable?

If not, is it okay to make a class, and define a function. Store the class as the variable and invoke that function?

3
Contributors
4
Replies
12
Views
6 Years
Discussion Span
Last Post by ultimatebuster
0

Not unless you are going to use "exec()" and people advise against that.

The second way is a good way.

class Test:
    def Testing(self):
        # Run function

x = Test()
x.Testing()
0

Simply store the reference to the function in the variable. Here is example:

def one():
    print("hello from function one")

def two():
    print("hello from function two")

def three():
    print("hello from function three")

# stores the ref of function in variable
f1 = one
f2 = two
f3 = three
func_list = [f1, f2, f3]

for f in func_list:
    # show the function reference
    print(f)
    # call the function
    f()

"""my display -->
<function one at 0x01DFE150>
hello from function one
<function two at 0x01DFE198>
hello from function two
<function three at 0x01DFE108>
hello from function three
"""
0

Simply store the reference to the function in the variable. Here is example:

def one():
    print("hello from function one")

def two():
    print("hello from function two")

def three():
    print("hello from function three")

# stores the ref of function in variable
f1 = one
f2 = two
f3 = three
func_list = [f1, f2, f3]

for f in func_list:
    # show the function reference
    print(f)
    # call the function
    f()

"""my display -->
<function one at 0x01DFE150>
hello from function one
<function two at 0x01DFE198>
hello from function two
<function three at 0x01DFE108>
hello from function three
"""

I never knew I could do that. I knew you could do it with a class instance but...thanks

This question has already been answered. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.