Python:具有相同名称的函数和变量 [英] Python: function and variable with same name
问题描述
我的问题是为什么我不能再次调用该函数?或者,如何做到这一点?
假设我有这个功能:
def a(x,y,z):
如果x:
返回y
else:
返回z
我将它称为:
打印a(3> ; 2,4,5)
我得到4个。
但想象一下,我声明了一个与该函数名称相同的变量(错误):
a = 2
现在,如果我尝试这样做:
$ b $ (3> 4,4,5)
我会得到这样的错误:TypeError:'int'object is callable
无法将变量'a'分配给函数?
执行此操作后:
a = 2
a
不再是 function ,它只是一个整数(你重新分配了它!)。所以很自然,如果你试图像调用函数一样调用它,解释器会发出抱怨,因为你这样做:
2()
=> TypeError:'int'对象不可调用
底线:您不能拥有两件东西同时具有相同的名称,可以是Python中的函数,整数或任何其他对象。只需使用其他名称即可。
My question is why I can't call the function again? Or, how to make that?
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"
It's not possible to assign the variable 'a' to the function?
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.
这篇关于Python:具有相同名称的函数和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!