Python类调用其他方法

标签 python class methods

我不明白为什么这段代码不起作用:

import numpy as np 

class Normalizer:
    def __init__(self,x):
        self.x = x 
    def mean(self):
        return np.sum(self.x)/np.size(self.x)
    def mean_zero(self):
        return self.x - self.x.mean()
    def new_calc(self):
        return self.x.mean_zero()

    a = np.random.randint(150,200,(5,8))

    heights = Normalizer(a)


    print(a)
    print(heights.mean()) 
    print(heights.mean_zero())
    print(heights.mean_zero().mean())
    print(heights.new_calc())

它正确执行 heghts.mean_zero() 但在方法 def new_calc(self) 中它不执行它。如果有人可以向我解释这一点,那就太好了。谢谢!

最佳答案

I don't understand why this code doesn't work:

如果运行以下代码,它将引发错误:

AttributeError: 'numpy.ndarray' object has no attribute 'mean_zero'
  • 定位问题,唯一调用了mean_zero的地方是new_calc方法。这样,第一步就完成了。

  • 分析一下,如果您查看 Normalize 类,它有一个属性 x,其类型为 numpy.ndarray。如果您仔细阅读错误消息,它会显示 ndarray 类型没有属性 mean_zero。另一方面,您在类中定义了 mean_zero 方法,这是您应该调用的方法。

这两个步骤得出的结论是问题出在 new_calc 方法中:

def new_calc(self):
    return self.mean_zero() #(wrong)return self.x.mean_zero()

关于Python类调用其他方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474646/

相关文章:

python - 为什么这两种对二维数组求和的不同方法具有如此不同的性能?

python - 列表列表,最后一项与python比较

javascript - Meteor SimpleSchema + 方法 : clicking too fast throw an error

python - 在 Linux 中以编程方式检查特定类型的设备

asp.net - 如何在 Visio 中创建 Visual Studio 风格的类图?

python - 更改静态类变量

C++ 类继承 : Functions

asp.net - 如何在 ASP.Net 中执行 <form method ="get"> 搜索表单?

java - 这是我收到的错误 : Type mismatch: cannot convert from double to double[]

Python 2.7 嵌套的 If 语句在打印数组位置后不会打印字符串文字