How does Python3 know what to select?

Hi,
In the example code below that I have pasted from Learn Python3 >Files >exercise 13/14, how does the code ‘know’ or ‘select’ that it must run the repr() and not the other init() dunder ??


class Employee():
def init(self, name):
self.name = name

def repr(self):
return self.name

argus = Employee(“Argus Filch”)
print(argus)

prints “Argus Filch”


https://www.codecademy.com/courses/learn-python-3/lessons/data-types/exercises/string-representation

Hi,
The dunder methods are built-in methods. So, under the hood, python is dealing with each in a predefined way.
So, the init (which is also known as a constructor), is only use when you first create an instance of on object. It takes in the arguments you give it and sets up the initial state of the object.
The repr method, by default, just displays what the object is and its memory address;
e.g.

<__main__.Employee object at 0x000001F51B3313A0>

But, as your example displays, you can overwrite this by creating your own repr method to create something which may be more useful.

Hope that helps

2 Likes