Python类调用其他方法

2024-04-25 08:31:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)中它不执行它。如果有人能向我解释一下就太好了。谢谢!你知道吗


Tags: 代码importselfnumpynewreturndefas
3条回答

我不确定来自__init__x是什么,但很可能您真的想在self变量(同一对象)的上下文中调用mean_zero

def new_calc(self):
        return self.mean_zero()

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()

代替self.x.mean_zero()写入自身平均值()

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.mean()
   def new_calc(self):
       return self.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())

相关问题 更多 >

    热门问题