python - 类型错误 : Mean() missing 1 required positional argument: 'data'

标签 python python-3.x anaconda

我正在尝试使用类编写一个基本的均值计算器。但是,我收到了错误

TypeError: Mean() missing 1 required positional argument: 'data'

我有两个文件:一个包含带有 mean 函数的类,另一个调用它,这就是我遇到错误的时候。我的代码是:

class Statistics:
    def __init__(self,mean_x,mean_y,var,covar):
        self.mean_x=mean_x
        self.mean_y=mean_y
        self.var=var
        self.covar=covar
    
    def Mean(self,data):
        return sum(data)/float(len(data))

抛出错误的代码是:

from Statistics import Statistics 
X=(0,1,3,5)
mean_x=Statistics.Mean(X)
print(mean_x)

最佳答案

Mean 是一个实例方法,因此您需要在实例上调用它(它将成为方法调用的 self 参数)。

statistics = Statistics(None, None, None, None)
mean_x = statistics.Mean((0, 1, 3, 5))

由于未使用 Statistics.__init__ 上的参数,因此我建议删除它们(或者干脆删除 __init__):

class Statistics:
   
    def mean(self, data):
        return sum(data)/float(len(data))
from Statistics import Statistics 
X = (0,1,3,5)
statistics = Statistics()
mean_x = statistics.mean(X)
print(mean_x)

请注意,Python 附带一个 statistics 模块,该模块内置了一个 mean 函数:

import statistics

X = (0,1,3,5)
mean_x = statistics.mean(X)
print(mean_x)

关于python - 类型错误 : Mean() missing 1 required positional argument: 'data' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71038415/

相关文章:

python - 使用 pandas 中的另一列替换一列中的值的有效方法

Python itertools.groupby() 使用具有多个键的元组

python - 在 Dataframe 中删除行时出现 IndexError

python - 如何在 pandas 中将 m×m 数据帧转换为 m*m×3 数据帧?

json - 来自单列中嵌套字典的 Pandas 数据框

python - 键入 "PermissionError"以离开 Python 解释器时抛出 "exit()"

python - 为什么 Conda 不安装/更新最新版本的 Spyder?

python - 如何比较两个集合,其中每个元素都是列表?

python - 如何通过文本在PyQt中为QTableView创建过滤器

python - 安装anaconda时如何pip安装python包?