python object has no attribute '__getitem__'

class Animal(object):
        def __init__(self, name):
                self.name = name


a1 = Animal("panda")

print a1['name']

当执行

a1['name']

出现如下问题:

Traceback (most recent call last):
File “test.py”, line 19, in
print a1[‘name’]
TypeError: ‘Animal’ object has no attribute ‘getitem

提示没有定义__gettiem__

解决办法:

为类定义__gettiem__方法;

class Animal(object):
        def __init__(self, name):
                self.name = name

        def __getitem__(self, k):
                if k == 'name':
                        return self.name


a1 = Animal("panda")

print a1['name']

再次执行,得到如下output:

panda

你可能感兴趣的:(python,python,getitem)