简体   繁体   中英

Python: How can I call a function that has another function as argument?

I have:

beta  = 0.95
alpha = 0.3
delta = 0.1

def k_bar(alpha, beta, delta):
    return ((1 / beta - 1 + delta) / alpha) ** (1 / (alpha - 1))
def c_bar(alpha, delta, k_bar):
    return k_bar ** alpha  - delta * k_bar

When i call

k_bar(alpha, beta, delta)

I get "2.63". But but when i call

c_bar(alpha, delta, k_bar) 

I get "TypeError: unsupported operand type(s) for ** or pow(): 'function' and 'float'"

However I would like to get the result instead and make the function as argument work in this specific case.

I hope sb. can help me!

Cheers, Tobias

I suspect that what you actually want to do is have c_bar call k_bar , like this:

def k_bar(alpha, beta, delta):
    return ((1 / beta - 1 + delta) / alpha) ** (1 / (alpha - 1))

def c_bar(alpha, beta, delta):
    k = k_bar(alpha, beta, delta)
    return k ** alpha  - delta * k

You can call it the same way you call k_bar :

c = c_bar(alpha, beta, delta)

This call will automatically invoke k_bar for you.


As ACascarino rightly points out, you should note that the alpha, beta, delta you define as the function arguments are different to the global variables you define at the top. Inside the function, alpha will refer to the function argument.

I think you have some problem on what is a function.

According your comments, you want to do:

 k_bar = ((1 / beta - 1 + delta) / alpha) ** (1 / (alpha - 1))

which is not a function.

[A short trick for beginner, never use the same variable name for two different things (like tour alpha, k_bar). I make you much more difficult to find the error: you expect in one place, but it is in an other place].

If you send a function as argument, fine, but than it remain a function, so it needs the parameters:

def c_bar(alpha, delta, k_bar):
    return k_bar(alpha, beta, delta) ** alpha  - delta * k_bar(alpha, beta, delta)

Note: delta in not defined inside c_bar.

Just call:

c_bar(alpha, delta, k_bar(alpha, beta, delta))

This way you pass the returned value of k_bar to c_bar

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