Nick <nleio...@gmail.com> wrote: > this is the new oop version, its pretty messy currently, and i do > understand it is a simple routine, but i'm using it as an exercise to > learn oop python... > > first the (current) traceback: > [:~/python]$ python oop_covariance.py b2ar_all_test b2ar_all_test > <Eigen.Eigen_vect instance at 0x7fa26c404ab8> > <Eigen.Eigen_vect instance at 0x7fa26c404ab8> > Traceback (most recent call last): > File "oop_covariance.py", line 24, in <module> > cov = set1.covariance(set2, Eigen_vect.dot) > File "/home/nleioatts/python/Eigen.py", line 66, in covariance > print self.vectors[i][i] > AttributeError: Eigen_vect instance has no attribute '__getitem__'
You are trying to use your Eigen_vect class as an array. In order for an object to act as an array it needs a __getitem__ method. > class Eigen_vect: > def __init__(self, e_val, e_vect): > self.e_val = e_val > self.e_vect = e_vect > def length(self): > return len(self.e_vect) > > def dot(self, other): > d = 0.0 > if other.length() != self.length(): > raise ValueError, "Eigen Vectors not same Length" > for k in range(self.length()): > # print "HI NICK", self.e_vect[k], other.e_vect[k] > d += float(self.e_vect[k]) * float(other.e_vect[k]) > return d Either add a __getitem__ method like this def __getitem__(self, n): return self.e_vect[n] Or you might want to subclass list if you are going to do a lot of list like operations on Eigen_vects, eg class Eigen_vect(list): def __init__(self, e_val, e_vect): self.e_val = e_val self[:] = e_vect def dot(self, other): d = 0.0 if len(other) != len(self): raise ValueError("Eigen Vectors not same Length") for a, b in zip(self, other): d += float(a) * float(b) return d Notice that now these things are lists, you can use len, zip etc on them which makes the code much neater. e = Eigen_vect(3, range(10)) f = Eigen_vect(4, range(1,11)) print e print f print e[2] print e.dot(f) Which prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 2 330.0 -- Nick Craig-Wood <n...@craig-wood.com> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list