我有一些针对特定attr的自定义getter的类:
class Item(a, b, c, d, models.Model):
title = Field()
description = Field()
a = Field()
_custom_getter = ['title','description']
def __getattribute__(self, name):
if name in self.custom_getter:
return 'xxx'
else:
return super(Item, self).__getattribute__(name)
此代码引发RunetimeError
:maximum recursion depth exceeded while calling a Python object
但是当我使用这段代码时:
class Item(a, b, c, d, models.Model):
title = Field()
description = Field()
a = Field()
def __getattribute__(self, name):
custom_getter = ['title','description']
if name in custom_getter:
return 'xxx'
else:
return super(Item, self).__getattribute__(name)
一切都像我想要的那样。第一段代码中我的错误是什么?
答案 0 :(得分:3)
执行__getattribute__
时会调用self.custom_getter
。您可以使用self.__dict__
。阅读更多How is the __getattribute__ method used?
class Item(a, b, c, d, models.Model):
title = Field()
description = Field()
a = Field()
custom_getter = ['title','description']
def __getattribute__(self, name):
if name in self.__dict__['custom_getter']:
return 'xxx'
else:
return super(Item, self).__getattribute__(name)