I was wondering if it is possible in python to do the following:
def func1(a,b): return func2(c,d)
What I mean is that suppose I do something with a,b which leads to some coefficients that can define a new function, I want to create this function if the operations with a,b is indeed possible and be able to access this outside of func1.
An example would be a simple fourier series, F(x), of a given function f:
def fourier_series(f,N): ...... math here...... return F(x)
What I mean by this is I want to creat and store this new function for later use, maybe I want to derivate it, or integrate or plot or whatever I want to do, I do not want to send the point(s) x for evaluation in fourier_series (or func1(..)), I simply say that fourier_series creates a new function that takes a variable x, this function can be called later outside like y = F(3)... if I made myself clear enough?
Python may return functions from functions, store functions in collections such as lists and generally treat them as you would any variable or object. Defining functions in other functions and returning functions are all possible.
In the Python programming language, a user can return multiple values from a function.
__init__ method returns a value The __init__ method of a class is used to initialize new objects, not create them. As such, it should not return any value. Returning None is correct in the sense that no runtime error will occur, but it suggests that the returned value is meaningful, which it is not.
You should be able to do this by defining a new function inline:
fourier_series(f, N): def F(x): ... return F
You are not limited to the arguments you pass in to fourier_series
:
def f(a): def F(b): return b + 5 return F >>> fun = f(10) >>> fun(3) 8
You could use a lambda
(although I like the other solutions a bit more, I think :) ):
>>> def func2(c, d): ... return c, d ... >>> def func1(a, b): ... c = a + 1 ... d = b + 2 ... return lambda: func2(c,d) ... >>> result = func1(1, 2) >>> print result <function <lambda> at 0x7f3b80a3d848> >>> print result() (2, 4) >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With