Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Python: function and variable with the same name

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...