' NoneType'对象不支持在定义__getattribute__方法时发生的项目赋值

时间:2016-03-28 05:25:58

标签: python python-3.x

我是Python的新手。最近,我一直在阅读Python类的内置方法。这是问题所在:

class Test:
    def __setattr__(self, key, value):
        self.__dict__[key] = value

    def __getattribute__(self, item):
        pass

if __name__ == '__main__':
        T = Test()
        setattr(T, 'xx', 33)
        print(getattr(T, 'xx'))

当我运行此脚本时,收到错误消息:

TypeError: 'NoneType' object does not support item assignment

但是当我删除__getattribute__方法时,一切正常。 我不知道这是怎么发生的。为什么__getattribute__方法会影响对象T的数据类型?

2 个答案:

答案 0 :(得分:1)

这是因为当您尝试获取对象的属性时始终会调用__getattribute__方法:

t=Test()
print(t.attribute)

但是在__setattr__方法中,您正在使用__getattribute__

def __setattr__(self, key, value):
    self.__dict__[key]=value  #__getattribute__("__dict__") is called

但是 getattribute 返回None(pass什么也不做,所以默认情况下它返回None) 然后你试图将一个项目分配给None,但这不起作用,所以有一个例外。 我希望现在一切都很清楚

问候,MrP01:)

答案 1 :(得分:0)

您正在覆盖默认的__getattribute__方法。您的方法定义中的pass将返回None。

因此,当在内部调用getattr(T, 'xx')时,会调用覆盖的方法返回None

相关问题