简体   繁体   中英

Passing variables into a function Python

I have the following situation: I have a single master_function that I wish to pass a sub_function into. The function that I wish to pass into this changes (for example 1 and 2). The arguments of each function also vary in their number and type.

def sub_function_1( x, y, z):
   return x + y + z

def sub_function_2( x, y ):
   return x + y 

def master_function( x, y, z, F ): 
   return x*y + F()

Quick fix

The simple fix to this would be to write the function callback with all possible arguments, whether they are used or not:

   def master_function( x, y, z, F ): 
       return x*y + F(x,y,z)

Then we can call master_function( x, y, z, sub_function_1) or master_function( x, y, z, sub_function_2) as desired.

Unfortunately, I have many functions that I wish to pass into the master function; so this approach is not suitable!

Is there a way to write F in master_function without reference to the arguments required? How can I generalise this?

The best way would be to just make the calls constant

def sub_function_1( x, y, z):
    return x + y + z

def sub_function_2( x, y, z ):
    return x + y 

def master_function( x, y, z, F ): 
    return x * y + F(x,y,z) 

But you can have it be more dynamic if you like:

def sub_function_1( x, y, z, **kwargs):
    return x + y + z

def sub_function_2( x, y, **kwargs ):
    return x + y 

def master_function( x, y, z, F ): 
    return x * y + F(**locals())

This works better in Python 3 potential as:

def sub_function_1(*args):
    return args[0] + args[1] + args[2]

def sub_function_2(*args):
    return args[0] + args[1] 

def master_function(*args, F): 
    return args[0] * args[1] + F(*args) 
.
.
.
>>> master_function(1,2,3,F=sub_function_1)
8
>>> master_function(1,2,3,F=sub_function_2)
5
>>> master_function(1,2,F=sub_function_2)
5
>>> master_function(1,2,F=sub_function_1)
IndexError: tuple index out of range

Here is your code, updated per the duplicate I mentioned.

def sub_function_1( x, y, z):
   return x + y + z

def sub_function_2( x, y ):
   return x + y 

def master_function(*args):
   F = args[-1]
   F_args = args[:-1]
   x = args[0]
   y = args[1]

   return x*y + F(*F_args)

print(master_function(1, 2, 3, sub_function_1))
print(master_function(-10, -20, sub_function_2))

Output:

8
170

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