1

I have some class with custom getter for specific attr:

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)

this code raise RunetimeError: maximum recursion depth exceeded while calling a Python object but when i use this piece of code:

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)

all works like I want. Wher is my mistake in first piece of code ?

gargi258
  • 829
  • 1
  • 10
  • 16

1 Answers1

3

Because __getattribute__ gets called when you do self.custom_getter. You can use self.__dict__ for this. Read more 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)
Community
  • 1
  • 1
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • I use `object.__getattribute__(self, '_custom_getter')` instead `self.__dict__['_custom_getter']` because it generate same error, but thanks for article, I found solution ther. – gargi258 Oct 12 '16 at 08:16