What do self, __init__, __repr__, __str__ and __len__ do?
selfrepresents the specific object instance you are currently creating or manipulating. Python uses it to bind attributes and methods to that unique instance. self is not a reserved keyword in Python, but it is a strict community standard.
classStudent:
def__init__(self, name):
self.name = name # self links the 'name' variable to this specific student
alex = Student("Alex")
print(alex.name) # Output: Alex
__init__initializes an object's attributes immediately after it is created. It automatically runs whenever you instantiate a new object from a class.
classCar:
def__init__(self, color):
self.color = color # Automatically assigns the color when born
my_car = Car("Red")
print(my_car.color) # Output: Red
__str__ is for end-users: It provides a clean, user-friendly description. It triggers when you call print() or str().
__repr__ is for developers: It provides an unambiguous, developer-friendly string representation of an object. Its primary goal is to aid in debugging and logging. The string returned by repr look like a valid Python expression that can be used to recreate the object when passed to eval().
classBook:
def__init__(self, title, author):
self.title = title
self.author = author
def__str__(self):
returnf"'{self.title}' by {self.author}"def__repr__(self):
returnf"Book('{self.title}', '{self.author}')"
my_book = Book("1984", "George Orwell")
print(str(my_book)) # Output: '1984' by George Orwell (User friendly)print(repr(my_book)) # Output: Book('1984', 'George Orwell') (Dev friendly)
__len__lets you use Python's built-in len() function directly on your custom objects. It must always return a non-negative integer. It calculates the size/length of an object.
classTeam:
def__init__(self, members):
self.members = members
def__len__(self):
returnlen(self.members) # Maps len() to the internal list length
avengers = Team(["Iron Man", "Thor", "Hulk"])
print(len(avengers)) # Output: 3