Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cryptic python error 'classobj' object has no attribute '__getitem__'. Why am I getting this?

I really wish I could be more specific here but I have read through related questions and none of them seem to relate to the issue that I am experiencing here and I have no understanding of the issue i am experiencing. This is for a homework assignment so I am hesitant to put up all my code for the program, here is a stripped down version. Compile this and you will see the issue.

import copy

class Ordering:

    def __init__(self, tuples):

        self.pairs = copy.deepcopy(tuples)
        self.sorted = []
        self.unsorted = []

        for x in self.pairs:
            self.addUnsorted(left(x))
            self.addUnsorted(right(x))

    def addUnsorted(self, item):

        isPresent = False

        for x in self.unsorted:
            if x == item:
                isPresent = True

        if isPresent == False:
            self.unsorted.append(left(item))

Here I have created a class, Ordering, that takes a list of the form [('A', 'B'), ('C', 'B'), ('D', 'A')] (where a must come before b, c must come before b, etc.) and is supposed to return it in partial ordered form. I am working on debugging my code to see if it works correctly but I have not been able to yet because of the error message I get back.

When I input the follwing in my terminal:

print Ordering[('A', 'B'), ('C', 'B'), ('D', 'A')]

I get back the following error message:

Traceback (most recent call last): File "<stdin>", line 1, in (module) Type Error: 'classobj' object has no attribute '__getitem__'

Why is this?!

like image 656
GnUfTw Avatar asked Aug 02 '26 19:08

GnUfTw


1 Answers

To access an element of a list, use square brackets. To instantiate a class, use parens.

In other words, do not use:

print Ordering[('A', 'B'), ('C', 'B'), ('D', 'A')]

Use:

print Ordering((('A', 'B'), ('C', 'B'), ('D', 'A')))

This will generate another error from deeper in the code but, since this is a homework assignment, I will let you think about that one a bit.

How to use __getitem__:

As a minimal example, here is a class that returns squares via __getitem__:

class HasItems(object):
    def __getitem__(self, key):
        return key**2

In operation, it looks like this:

>>> a = HasItems()
>>> a[4]
16

Note the square brackets.

like image 120
John1024 Avatar answered Aug 04 '26 13:08

John1024