修复 Python 中浮点对象无法调用的错误

Manav Narula 2022年5月17日
修复 Python 中浮点对象无法调用的错误

函数可以被认为是可重用的代码,可以在程序的任何地方调用和使用。我们只能在 Python 中调用函数。

要调用函数,我们在函数名称中使用括号。为函数提供的任何参数或参数都在这些括号内指定。

Python 中的 float object is not callable 错误以及如何解决

本教程将讨论 Python 的 float object is not callable 错误。

这是一个 TypeError,它表示某些无效操作与给定对象相关联。在 Python 中,我们只能调用函数。此错误表明正在调用 float 对象。

例如,

a = 1.5
a()

输出:

TypeError: 'float' object is not callable

在上面的例子中,我们得到了错误,因为我们创建了一个 float 变量 a 并试图调用它。我们现在将讨论可能发生此类错误的各种场景。

在 Python 中,我们有时会执行复杂的复杂操作,并且可能会使用括号来分隔运算符和操作数。有时,人们可能会将括号放在错误的位置,这似乎代表了一个函数调用语句。

例如,

a = 1.5
b = 5
c = 8 * 10 / 5 * a(2) * 5
print(c)

输出:

TypeError: 'float' object is not callable

我们需要注意括号并相应地放置操作数来解决这个问题。这是对前面示例的简单修复,如下所示。

a = 1.5
b = 5
c = 8 * 10 / 5 * (a * 2) * 5
print(c)

输出:

240.0

现在让我们讨论另一种情况。请参阅下面的代码。

def mul(a, b):
    return a * b


mul = mul(7, 4.2)
print(mul)

mul = mul(13, 8.2)
print(mul)

输出:

29.400000000000002
TypeError: 'float' object is not callable

在上面的示例中,我们创建了一个函数,然后将它分配给同名变量两次。

这适用于第一次调用,但返回 float object is not callable 是由于第二次函数调用引起的。发生这种情况是因为函数在第二个函数调用语句中被变量名覆盖。

它也有一个简单的修复。我们应该更改函数的名称或变量来解决这个错误。

请参阅下面的代码。

def mul_cal(a, b):
    return a * b


mul = mul_cal(7, 4.2)
print(mul)

mul = mul_cal(13, 8.2)
print(mul)

输出:

29.400000000000002
106.6
作者: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

相关文章 - Python Float

相关文章 - Python Error