Why I am getting error by placing self in the __repr__ method in the class in python?

24 Views Asked by At

Why I am getting error by placing self in the repr method in the class? What is happening behind the scene when I print(Employee.list_objects[0]). Why I am getting error?

class Employee:
    list_objects = []

    def __init__(self,name,age,pay):
        self.name=name
        self.age=age
        self.pay=pay
        Employee.list_objects.append(self)

    def __repr__(self):
        return f'{self} {self.name}, {self.age}, {self.pay})'

Employee1=Employee("Ali",23,50000)
Employee2=Employee("John",25,40000)
Employee3=Employee("Smith",29,70000)


print(Employee.list_objects[0])

Ouptut:

Traceback (most recent call last):
  File "f1.py", line 19, in <module>
    print(Employee.list_objects[0])
  File "f1.py", line 11, in __repr__
    return f'{self} {self.name}, {self.age}, {self.pay})'
  File "f1.py", line 11, in __repr__
    return f'{self} {self.name}, {self.age}, {self.pay})'
  File "f1.py", line 11, in __repr__
    return f'{self} {self.name}, {self.age}, {self.pay})'
  [Previous line repeated 330 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

Why I am getting error by placing self in the repr method in the class? What is happening behind the scene when I print(Employee.list_objects[0]). Why I am getting error?

0

There are 0 best solutions below