Magic Methods Overview

Show common magic methods like __str__ and __len__.

IntermediateTopic: Object-Oriented Programs
Back

Python Magic Methods Overview Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to demonstrate some magic methods

class BookCollection:
    def __init__(self, books):
        self.books = books

    def __len__(self):
        return len(self.books)

    def __str__(self):
        return ", ".join(self.books)


bc = BookCollection(["Python 101", "OOP in Python"])
print(len(bc))
print(bc)
Output
2
Python 101, OOP in Python

Understanding Magic Methods Overview

Implementing __len__ and __str__ customizes how len() and print() behave for the class.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents