【问题标题】:Cryptic python error 'classobj' object has no attribute '__getitem__'. Why am I getting this?神秘的 python 错误“classobj”对象没有属性“__getitem__”。为什么我会得到这个?
【发布时间】:2014-12-01 09:10:05
【问题描述】:

我真的希望我能在这里更具体一点,但我已经阅读了相关问题,但似乎没有一个与我在这里遇到的问题有关,而且我不了解我遇到的问题。这是一个家庭作业,所以我犹豫是否要为该程序提供所有代码,这是一个精简版。编译这个,你会看到问题。

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

在这里,我创建了一个类 Ordering,它采用 [('A', 'B'), ('C', 'B'), ('D', 'A')] 形式的列表(其中 a 必须在 b 之前,c 必须在 b 之前,等等)并且应该以偏序形式返回它。我正在调试我的代码以查看它是否正常工作,但由于我收到的错误消息,我还不能。

当我在终端中输入以下内容时:

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

我收到以下错误消息:

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

这是为什么?!

【问题讨论】:

  • 您可能已经注意到,您的演示代码使用了未定义的函数left()right()

标签: class python-2.7 object types instantiation


【解决方案1】:

要访问列表的元素,请使用方括号。要实例化一个类,请使用括号。

换句话说,不要使用:

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

用途:

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

这将在代码的更深处产生另一个错误,但由于这是一项家庭作业,我会让你考虑一下。

如何使用__getitem__:

作为一个最小的例子,这是一个通过__getitem__返回正方形的类:

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

运行中是这样的:

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

注意方括号。

【讨论】:

  • 感谢您的快速回复。我的错误是我忘记了括号来将我的论点附在课堂上。也感谢 getitem 的例子,很有意义。
【解决方案2】:

回答“为什么会这样?”

您的演示代码不完整(参考上面的评论),但是 .__getitem__ 方法的问题显然与 print 对象的声明有关(由于其他原因确实未能响应响应调用.__getitem__ 方法的请求)而不是类本身。

>>> aList = [ ('A','B'), ('C','D'), ('E','F')]       # the stated format of input
>>> aList                                            # validated to be a list
[('A', 'B'), ('C', 'D'), ('E', 'F')]
>>> type( aList )                                    # cross-validated
<type 'list'>
>>> for x in aList:                                  # iterator over members
...     print x, type(  x )                          # show value and type
...     left( x )                                    # request as in demo-code
...
('A', 'B') <type 'tuple'>
Traceback (most recent call last):                   <<< demo-code does not have it
  File "<stdin>", line 3, in <module>
NameError: name 'left' is not defined


>>> dir( Ordering )                                  # .__getitem__ method missing
[ '__doc__', '__init__', '__module__', 'addUnsorted']


>>> dir( aList[0] )                                  # .__getitem__ method present
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
 '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
 '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
 '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
 '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
 'count', 'index']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多