我不明白为什么这段代码不起作用:
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/