Question

Why can't I call the function again? Or, how can I make it?

Suppose I have this function:

def a(x, y, z):
 if x:
     return y
 else:
     return z

and I call it with:

print a(3>2, 4, 5)

I get 4.

But imagine that I declare a variable with the same name that the function (by mistake):

a=2

Now, if I try to do:

a=a(3>4, 4, 5)

or:

a(3>4, 4, 5)

I will get this error: "TypeError: 'int' object is not callable"

Is it not possible to assign the variable 'a' to the function?

Was it helpful?

Solution

After you do this:

a = 2

a is no longer a function, it's just an integer (you reassigned it!). So naturally the interpreter will complain if you try to invoke it as if it were a function, because you're doing this:

2()
=> TypeError: 'int' object is not callable

Bottom line: you can't have two things simultaneously with the same name, be it a function, an integer, or any other object in Python. Just use a different name.

OTHER TIPS

names in Python are typically identifiers for a specific type, more like naming a box which stores a variable/function/method or any object in Python. When you are reassigning, you are just renaming a box.

You can find that out by doing the below.

Initially, a is assigned a value 9, at location 140515915925784. As soon as I use the same identifier for a function , a now refers to a box containing the address of that function in 4512942512

Reassigning a to 3 again points a to refer to a different address.

>>> a = 9
>>> id(a)
140515915925784
>>> def a(x):
...     return x
...
>>> id(a)
4512942512
>>> a
<function a at 0x10cfe09b0>
>>>
>>>
>>>
>>> a = 3
>>> id(a)
140515915925928
>>> a
3
>>>

You're assigning the name a to a function definition, and then reassigning it to an integer.

It's syntactically correct, but it's not what you want.

It's best to give functions semantic names that describe what you're doing with the arguments being passed to them, and to give variables semantic names that describe what object they're pointing to. If you do that, you'll have more readable code and you certainly won't make this mistake again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top