I don't understand why this code doesn't work:
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())
It executes heghts.mean_zero() correctly but in the method def new_calc(self) it doesn't execute it. It would be great if someone could explain that to me. Thanks!
5 Answers 5
I don't understand why this code doesn't work:
if you run the following code it will throw an error:
AttributeError: 'numpy.ndarray' object has no attribute 'mean_zero'
locate the problem, the only place where
mean_zerohas been called isnew_calcmethod. So, first step done.analyze, if you look at
Normalizeclass it has one attributexwhich is of the typenumpy.ndarray. If you carefully read the error message it says thatndarraytype doesn't have the attributemean_zero. On the other hand you havemean_zeromethod defined in your class and that is the one you should call.
These two steps leads to conclusion that the problem is in new_calc method:
def new_calc(self):
return self.mean_zero() #(wrong)return self.x.mean_zero()
Comments
I am not sure what x from the __init__ is but it is very likely that you actually want to call mean_zero in new_calc in the context of self variable (the same object):
def new_calc(self):
return self.mean_zero()
Comments
Insted of self.x.mean_zero() write self.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())
Comments
You're initializing Normalizer with 'a', which is the output of np.random.randint, which returns a numpy.ndarray object.
In the new_calc method you are attempting to call the mean_zero method of the ndarray object, but ndarray has no such method. mean_zero is a method on Normalizer, but self.x is not of type Normalizer.
I'm not sure what this code new_calc is supposed to do. If you can make that clearer, I may be able to provide more assistance.
1 Comment
The culprit:
def new_calc(self):
return self.x.mean_zero()
The reason:
self.x is an attribute of the Normalizer class. So if heights is an instance of the Normalizer class, then heights.x is the self.x.
The answer:
def new_calc(self):
return self.mean_zero()
The justification:
AttributeError: 'numpy.ndarray' object has no attribute 'mean_zero'
ndarray has no such method. mean_zero is a method of Normalizer
self.mean_zero()instead ofself.x.mean_zero()