Search code examples
pythonattributeerror

Yet another "instance has no attribute '__getitem__' " case


This seems to have been beat to death on Stack Overflow but none of the questions seem to match my problem. Anyway, straight to the code.

This is Edge.py

from __future__ import division
import sys
from numpy import *


class EdgeList:
    def __init__(self, mat):
        self.id1 = mat[:,0]
        self.id2 = mat[:,1]
        self.value = mat[:,2]
    def is_above(self):
        return self.value>average(self.value)
    def stats(self):
        pass #omitted; too long and irrelevant here.

This is AHsparse.py

from __future__ import division

import sys
from numpy import *
from Edge import EdgeList

class AHvector:
    def __init__(self, mat):
        self.el = EdgeList(mat)
    def multiply(self, other):
        v=zeros(max(len(self.el.val), len(other.el.val)))
        for index in self.id1:
            v[index] = self.el.val[index] * other.el.val[index]
        return v

This is some test code (other tests pass)

import sys
from numpy import *
from Edge import EdgeList
from AHsparse import AHvector

testmat =loadtxt('test.data', delimiter=';')
st = EdgeList(testmat)
stv = AHvector(st)
stv = stv.multiply(stv)
print(stv)

The error happens at the init method of class AHvector, but calls back to Edge.py:

Traceback (most recent call last):
  File "/Users/syntaxfree/Dropbox/nina/nina lives in objects/sparse_test.py", line 8, in <module>
    stv = AHvector(st)
  File "/Users/syntaxfree/Dropbox/nina/nina lives in objects/AHsparse.py", line 9, in __init__
    self.el = EdgeList(mat)
  File "/Users/syntaxfree/Dropbox/nina/nina lives in objects/Edge.py", line 7, in __init__
    self.id1 = mat[:,0]
AttributeError: EdgeList instance has no attribute '__getitem__'
[Finished in 0.6s with exit code 1]

I have nothing else to add, I'm afraid -- except I'm able to initialize EdgeList on its own and run the stats method in other test code, and I'm thoroughly confused as why this wouldn't work.


Solution

  • When you run

     stv = AHvector(st)
    

    st is an Edgelist. Then AHvector's init tries to make an Edgelist of st. Maybe AHvector should state

     self.el = mat # Instead of EdgeList(mat)?
    

    or maybe AHvector isn't supposed to be receiving st, but rather testmat?