Assigning a function to a variable
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
.
Solution 1:
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
).
Solution 2:
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()
Solution 3:
when you perform y=x()
you are actually assigning y to the result of calling the function object x
and the function has a return value of None
. Function calls in python are performed using ()
. To assign x to y
so you can call y
just like you would x
you assign the function object x to y like y=x
and call the function using y()