Suman Mandal
Suman Mandal

Reputation: 5

How to pass parameter in another method?

So I have a method.

def func(y,t,a):
    z=y
    dydt=[t*z+a] 
    return dydt

I want to use this method in other function like this:

def main_func(func,arg=()):
    sol=func(1,2,arg[0])
    return sol
a=1
main_func(func,arg=(a))

It works but It will not work with the method which is like that

def new_func(y,t,a,b):
    z=y
    dydt=[t*z+a+b] 
    return dydt
a=1
b=2
main_func(new_func,arg=(a,b))

Got the error: TypeError: new_func() missing 1 required positional argument: 'b'

So, I have only thing to modify main_func.But I want to generalised the the function main_func for work with any function so that it will take other parameters func(y,t,a, b,.....)

Upvotes: 0

Views: 55

Answers (3)

Rishabh Kumar
Rishabh Kumar

Reputation: 2430

Unpacking only works with iterables like list,tuple etc. So to pass a single argument you need to pass it as:

main_func(func,arg=(a,)) OR main_func(func,arg=[a])

Just parenthesis over values are not considered tuples, so (a) is treated as a and is not a tuple.

To make it a tuple just add an extra , after a like : (a,)

That said,

You can use unpacking operator * like so,

def func(y,t,a):
    z=y
    dydt=[t*z+a] 
    return dydt

def new_func(y,t,a,b):
    z=y
    dydt=[t*z+a+b] 
    return dydt

def main_func(func,arg=()):
    sol=func(1,2,*arg)
    return sol

Output:

>>> a=1
>>> main_func(func,arg=(a,))
[3]

>>> a=1
>>> b=2
>>> main_func(new_func,arg=(a,b))
[5]

EDIT: If you don't want the arg argument to be an empty tuple in particular when no arguments are passed, you can keep *args as argument in main_func:

def main_func(func,*args):
    sol=func(1,2,*args)
    return sol
    

Output:

>>> a=1
>>> main_func(func,a)
[3]

>>> a,b=1,2
>>> main_func(new_func,a,b)
[5]

Upvotes: 1

Dead Guy
Dead Guy

Reputation: 57

I corrected the code and I think it may be the answer that you are looking for. THERE IS LOT OF MISTAKES IN YOUR CODE ABOVE.

my code:

def func(y,t,a):
    z=y
    #it return a list but I think it is intended to return a integer
    #dydt=[t*z+a] 
    #dydt = t*z+a
    return (t*z+a)

#got value of function when called this function
#we do not need func as argument
def main_func(arg):
    return (func(1,2,arg))

a=1
#using a not arg=(0)
#passing argument in function that you did not passed

main_func(func(1,2,a))

def new_func(y,t,a,b):
    z=y
    #dydt=[t*z+a+b] 
    return (t*z+a+b)
a=1
b=2
c=3
d=4


print (main_func(new_func(a,b,c,d)))

Upvotes: 0

jeremy302
jeremy302

Reputation: 828

The error is because new_func has an extra argument, b, so in your main_func, change how func is called:

def main_func(func,arg=()):
    sol=func(1,2,*arg)#or func(1,2,arg[0],arg[1])
    return sol

a=1
main_func(new_func,arg=(a,))#add an extra comma if there is only 1 item to tell python it is a tuple, or use a list like [a]

Upvotes: 0

Related Questions