Python: function and variable with the same name

My question is, why can't I call the function again? Or how to do 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 am declaring a variable with the same name as a 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: object" int "cannot be called"

Can't assign the variable 'a' to a function?

+12
function variables python
source share
4 answers

After that, do the following:

 a = 2 

a no longer a function, it's just an integer (you reassigned it!). Therefore, of course, the interpreter will complain if you try to call it, as if it were a function, because you are doing it:

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

On the bottom line: you cannot have two things at the same time with the same name, be it a function, an integer, or any other object in Python. Just use a different name.

+18
source share

names in python are usually identifiers for a particular type, more like naming a block that stores a variable / function / method or any object in python. When you reassign, you simply rename the window.

You can find out by following these steps.

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

Reassignment to a 3 times indicates to go to another address. a

 >>> 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 >>> 
+5
source share

You assign the name a to the definition of the function, and then assign it to an integer.

It is syntactically correct, but that is not what you want.

It’s best to give functions semantic names that describe what you are doing with the arguments passed to them and give semantic names for variables that describe which object they are pointing to. If you do this, you will have more readable code, and you probably will not repeat this error.

+4
source share

Why is it so, here the name of the variable and method are the same

def age: age = int (input ()) print (age)

age () 5 5

0
source share

All Articles