Python:具有相同名称的函数和变量 [英] Python: function and variable with the same name
问题描述
为什么我不能再次调用该函数?或者,我该怎么做?
Why can't I call the function again? Or, how can I make it?
假设我具有此功能:
def a(x, y, z):
if x:
return y
else:
return z
我这样称呼:
print a(3>2, 4, 5)
我得到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)
或:
a(3>4, 4, 5)
我将收到此错误:"TypeError:'int'对象不可调用"
I will get this error: "TypeError: 'int' object is not callable"
是否无法将变量"a"分配给该函数?
Is it not possible to assign the variable 'a' to the function?
推荐答案
执行此操作之后:
a = 2
a
不再是函数,而只是一个整数(您已将其重新分配!).因此,很自然,如果您尝试将其视为函数,则解释器会抱怨,因为您正在执行以下操作:
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
最重要的是:您不能同时拥有两个具有相同名称的东西,无论是函数,整数还是Python中的任何其他对象.只需使用其他名称即可.
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.
这篇关于Python:具有相同名称的函数和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!