+91 81900 98289

Python Magic Methods

This Python Magic Methods lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

Methods with two underscores on each side are hooks Python calls for you. __str__ shapes what print shows. __eq__ shapes ==.

Add one when your objects should work with a built-in operation. Do not invent new double-underscore names.

Example 1: Start here

__str__ is for people reading output. __repr__ is for a developer reading a log.

class Score: # a template for objects def __init__(self, value): # runs when you create the object self.value = value # store this on the object def __str__(self): # define the function; it runs when you call it return str(self.value) + " marks" # send this value back to the caller def __eq__(self, other): # define the function; it runs when you call it return self.value == other.value # send this value back to the caller print(Score(82)) print(Score(82) == Score(82)) # a comparison is True or False

Example 2: A readable object

__str__ decides what print shows.

class Course: # a template for objects def __init__(self, title): # runs when you create the object self.title = title # store this on the object def __str__(self): # define the function; it runs when you call it return "Course: " + self.title # send this value back to the caller print(Course("Python"))

Example 3: Length

__len__ lets the built-in len work on your object.

class Batch: # a template for objects def __init__(self, names): # runs when you create the object self.names = names # store this on the object def __len__(self): # define the function; it runs when you call it return len(self.names) # send this value back to the caller print(len(Batch(["Asha", "Arun"]))) # len counts the items

Example 4: Equal values

__eq__ defines what == means for this class.

class Score: # a template for objects def __init__(self, value): # runs when you create the object self.value = value # store this on the object def __eq__(self, other): # define the function; it runs when you call it return self.value == other.value # send this value back to the caller print(Score(82) == Score(82)) # a comparison is True or False
__str__ is for people reading output. __repr__ is for a developer reading a log.
Call Now 81900 98289