python object does not support item assignment

时间:2022-03-10 00:32:39

先看以下代码:

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


a1 = Animal("panda")

a1['age'] = 12

当执行到

a1['age'] = 12

报错:

Traceback (most recent call last):
File “test.py”, line 13, in <\module>
a1[‘age’] = 12
TypeError: ‘Animal’ object does not support item assignment

说明a1对象不可这样进行赋值操作;

解决办法:

需要为类定义__setitem__方法;

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


        def __setitem__(self, k, v):
                self.k = v

        def __str__(self):
                return "name:%s, %s" % (self.name, self.k)


a1 = Animal("panda")

a1['age'] = 12
print a1

再次执行,
output:

name:panda, 12

打印name以及刚赋值的12。