python函数名称可赋给其他变量,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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值