简体   繁体   English

为什么我会收到“浮动 object 不可调用”错误

[英]Why do I get 'Float object is not callable' error

I'm getting this error in my code:我的代码中出现此错误:

Test Failed: 'float' object is not callable.

My code is as follows:我的代码如下:

import math

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def std_dev(persons):
    persons_age = [person.age for person in persons]
    mean = float(sum(persons_age) * 1.0)/len(persons)
    length = float(len(persons))
    mean = float(mean(persons))
    total_sum = 0
    for i in range(length):
        total_sum += float(persons_age[i]- mean)**2
    square_root = float((total_sum * 1.0)/length)
    return math.sqrt(square_root)

This simple example reproduces your error:这个简单的示例重现了您的错误:

In [101]: x = 1.23                                                              
In [102]: x()                                                                   
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-102-08f9d0828de0> in <module>
----> 1 x()

TypeError: 'float' object is not callable

That means, some place in your code, you define a variable as a number, float.这意味着,在您的代码中的某个地方,您将变量定义为数字浮点数。 And then later you use that variable as though it were a function, with ().然后稍后您使用该变量,就好像它是一个 function,带有 ()。

The full traceback should identify which line and variable is the problem.完整的回溯应该识别出问题所在的行和变量。 But mean is a good guess.mean是一个很好的猜测。

What is this supposed to do?这应该做什么?

mean(persons)

There is a numpy.mean function, but not a base Python one.有一个numpy.mean function,但没有一个基础 Python 一个。

On an unrelated matter, you don't need all of those calls to float(...) .在不相关的问题上,您不需要所有这些对float(...)的调用。 In Py3, float division is the norm.在 Py3 中,浮点除法是常态。 So there's no harm in leaving integers that way.因此,以这种方式保留整数并没有什么坏处。 Normally you only need float if the argument is a string.通常,如果参数是字符串,则只需要float

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM