PHV
PHV

Reputation: 39

Google Colab - Infinite recursion error using __getattribute__,__getattr__ and __setattr__?

Suppose I have a class defined as follows:

class Employee:
  def __init__(self,val1,val2):
    print("In init")
    self.val1 = val1
    self.val2=val2
  def __setattr__(self,key,value):
    print("In setattr")
    #self.__dict__[key] = value # In order to access self.__dict__, __getattribute__ must be called
    super().__setattr__(key,value)

  def __getattr__(self,key):
    print("In getattr")
    y = str(input((f"No attribute found for {key}. Do you want to create one? ")))
    if y.lower() =='y':
      value = str(input("Enter value "))
      self.__setattr__(key,value)

  def __getattribute__(self,key):
    print("In getattribute")
    return super().__getattribute__(key)

Employee(1,2) returns a recursion error (in getattribute), which is a bit surprising because I have used super() wherever I believed it's required. Could someone please explain precisely why this error occurs and how do I get over this error? Thanks a lot!

Upvotes: 0

Views: 59

Answers (0)

Related Questions