Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a function to a variable

Tags:

python

Let's say I have a function

def x():     print(20) 

Now I want to assign the function to a variable called y, so that if I use the y it calls the function x again. if i simply do the assignment y = x(), it returns None.

like image 516
stensootla Avatar asked Apr 27 '12 16:04

stensootla


People also ask

Can you put a function in a variable?

we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; }; if we simply call this function, nothing will be printed, although nothing is wrong with the writing of the function itself.

How do you assign a function to a variable in C++?

In C++, assigning a function to a variable and using that variable for calling the function as many times as the user wants, increases the code reusability. Below is the syntax for the same: Syntax: C++

Can we assign function to variable in C?

File scope variables can only be initialised with constant expressions. A function call isn't one.

Can you assign a function to a variable in JavaScript?

It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} . But the function declaration function factorial(n) is compact (no need for const and = ). An important property of the function declaration is its hoisting mechanism.


2 Answers

You simply don't call the function.

>>>def x(): >>>    print(20) >>>y = x >>>y() 20 

The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns y the value returned by x (which in this case is None).

like image 124
Gareth Latty Avatar answered Sep 28 '22 05:09

Gareth Latty


When you assign a function to a variable you don't use the () but simply the name of the function.

In your case given def x(): ..., and variable silly_var you would do something like this:

silly_var = x 

and then you can call the function either with

x() 

or

silly_var() 
like image 44
Levon Avatar answered Sep 28 '22 05:09

Levon