- What are built-in methods — special methods that Python looks for
- __str__ — human-readable string representation
- __repr__ — developer-friendly representation
- __len__ — defining the length of objects
- __call__ — making objects callable like functions
- __bool__ — defining truth values
What are Built-in Class Methods?
Python comes with a set of special methods that give your classes superpowers. These methods are often called "magic methods" or "dunder methods" (because they have double underscores at the beginning and end). They let your objects behave like built-in Python types.
When you create a class, Python automatically provides these methods. But you can override them to customize how your objects work. This is what makes Python's object model so powerful and flexible.
Think of these methods like special abilities your objects can have. With __str__, your objects can print nicely. With __len__, your objects can tell you how long they are. Each method gives your class a new capability.
💡 Key concept: Built-in methods are special methods that Python looks for in your classes. They let your objects interact with Python's built-in functions and operators in a natural way.
__str__ — String Representation
The Human-Readable String
The __str__ method defines how your object should be displayed as a string. It's used by print(), str(), and f-strings. It should return a human-readable, user-friendly representation of your object.
# The __str__ method
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
def __str__(self):
"""Return a human-readable string representation"""
return f"{self.name} ({self.age}) from {self.city}"
# Without __str__, printing objects gives a default representation
class PersonWithoutStr:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating objects
person1 = Person("Alice", 25, "NYC")
person2 = PersonWithoutStr("Bob", 30)
# With __str__ - nice and readable
print(person1) # Alice (25) from NYC
print(str(person1)) # Alice (25) from NYC
# Without __str__ - default representation
print(person2) # <__main__.PersonWithoutStr object at 0x...>
# Using __str__ in f-strings
print(f"Person: {person1}") # Person: Alice (25) from NYC
# Using __str__ in string concatenation
print("The person is " + str(person1))
# __str__ makes your objects user-friendly
# It's what people see when they print your objects
__str__ key points:
- Human-readable — meant for users, not developers
- Called by print() — automatically used when printing
- Called by str() — used when converting to string
- Used in f-strings — formatting strings
- Should be clear — easy for humans to understand
Quick Check: When is __str__ called? (Answer: When printing an object or converting it to a string with str())
__repr__ — Developer Representation
The Developer-Friendly String
The __repr__ method defines a developer-friendly representation of your object. It's used by the Python interactive shell and when you call repr(). It should return a string that, ideally, could be used to recreate the object.
# The __repr__ method
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __repr__(self):
"""Return a developer-friendly representation"""
return f"Book('{self.title}', '{self.author}', {self.pages})"
def __str__(self):
"""Return a user-friendly representation"""
return f"'{self.title}' by {self.author} ({self.pages} pages)"
# Creating a book
book = Book("Python Guide", "John Smith", 350)
# __str__ - for users
print(book) # 'Python Guide' by John Smith (350 pages)
# __repr__ - for developers
print(repr(book)) # Book('Python Guide', 'John Smith', 350)
# In the Python interactive shell, typing the object name shows __repr__
# In a script, we use repr() to see it
# __repr__ should ideally be unambiguous
class Movie:
def __init__(self, title, director, year):
self.title = title
self.director = director
self.year = year
def __repr__(self):
return f"Movie('{self.title}', '{self.director}', {self.year})"
movie = Movie("The Matrix", "Wachowski", 1999)
print(repr(movie)) # Movie('The Matrix', 'Wachowski', 1999)
# __repr__ is often used for debugging
# It shows what the object is and what it contains
__repr__ key points:
- Developer-focused — meant for debugging and development
- Called by repr() — used in the interactive shell
- Should be unambiguous — should clearly identify the object
- Ideally recreatable — should show how to recreate the object
- Fallback for __str__ — if __str__ is not defined, Python uses __repr__
Quick Check: What is the difference between __str__ and __repr__? (Answer: __str__ is for users, __repr__ is for developers)
__len__ — Length of Objects
Defining What "Length" Means
The __len__ method defines what the length of your object means. It's called by the built-in len() function. It should return an integer representing the size or count of your object.
# The __len__ method
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def remove_item(self, item):
if item in self.items:
self.items.remove(item)
def __len__(self):
"""Return the number of items in the cart"""
return len(self.items)
def __str__(self):
return f"Shopping cart with {len(self)} items: {', '.join(self.items)}"
# Creating a shopping cart
cart = ShoppingCart()
cart.add_item("Apple")
cart.add_item("Banana")
cart.add_item("Orange")
# len() works with our object
print(len(cart)) # 3
print(cart) # Shopping cart with 3 items: Apple, Banana, Orange
# Another example: A playlist
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add_song(self, song):
self.songs.append(song)
def __len__(self):
return len(self.songs)
def __getitem__(self, index):
return self.songs[index]
playlist = Playlist("Favorites")
playlist.add_song("Song 1")
playlist.add_song("Song 2")
playlist.add_song("Song 3")
print(len(playlist)) # 3
print(f"{playlist.name} has {len(playlist)} songs")
# __len__ is used in boolean context
# If __len__ returns 0, the object is considered False
# If __len__ returns > 0, the object is considered True
if cart:
print("Cart has items") # This will print
# Empty cart
empty_cart = ShoppingCart()
if not empty_cart:
print("Cart is empty") # This will print
__len__ key points:
- Returns integer — the length or count of the object
- Called by len() — built-in len() function
- Used for truthiness — if __len__ returns 0, the object is False
- Should be efficient — avoid expensive computations
- Required for some operations — for loops, if conditions, etc.
Quick Check: What does __len__ return? (Answer: An integer representing the length of the object)
__call__ — Making Objects Callable
Objects That Act Like Functions
The __call__ method lets you use your object like a function. When you define __call__, your object becomes callable — you can use parentheses on it, just like a function.
# The __call__ method
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, number):
"""Make the object callable like a function"""
return number * self.factor
# Creating a multiplier
double = Multiplier(2)
triple = Multiplier(3)
# Using the objects like functions
print(double(5)) # 10
print(triple(5)) # 15
# Another example: A counter
class Counter:
def __init__(self, start=0):
self.count = start
def __call__(self):
"""Increment the counter and return the new value"""
self.count += 1
return self.count
# Creating a counter
counter = Counter(5)
print(counter()) # 6
print(counter()) # 7
print(counter()) # 8
# A more complex example: A logger
class Logger:
def __init__(self, prefix=""):
self.prefix = prefix
def __call__(self, message):
"""Log a message with a prefix"""
if self.prefix:
print(f"[{self.prefix}] {message}")
else:
print(message)
# Creating loggers
simple_logger = Logger()
error_logger = Logger("ERROR")
info_logger = Logger("INFO")
# Using them like functions
simple_logger("Hello, World!") # Hello, World!
error_logger("Something went wrong") # [ERROR] Something went wrong
info_logger("Process completed") # [INFO] Process completed
# __call__ is useful for:
# 1. Creating function-like objects
# 2. Maintaining state between calls
# 3. Creating closures in a class-based way
__call__ key points:
- Makes objects callable — objects can be used like functions
- Accepts arguments — like regular functions
- Can return values — like regular functions
- Maintains state — useful for counters, caches, etc.
- Common in decorators — decorators often use __call__
Quick Check: What does __call__ do? (Answer: It makes an object callable like a function)
__bool__ — Truth Value
Defining What's True and False
The __bool__ method defines the truth value of your object. It's called when your object is used in a boolean context — like in if statements, while loops, or with the bool() function.
# The __bool__ method
class Account:
def __init__(self, balance):
self.balance = balance
def __bool__(self):
"""Define when an account is considered True"""
return self.balance > 0
# Creating accounts
account1 = Account(100)
account2 = Account(0)
account3 = Account(-50)
# Using in boolean context
if account1:
print("Account 1 has money") # This will print
else:
print("Account 1 is empty")
if account2:
print("Account 2 has money")
else:
print("Account 2 is empty") # This will print
if account3:
print("Account 3 has money")
else:
print("Account 3 is empty") # This will print (negative balance is False)
# Another example: A shopping cart
class Cart:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def __bool__(self):
"""A cart is True if it has items"""
return len(self.items) > 0
cart = Cart()
if not cart:
print("Cart is empty") # This will print
cart.add_item("Apple")
if cart:
print("Cart has items") # This will print
# If __bool__ is not defined, Python uses __len__
# If __len__ returns 0, the object is False
# If __len__ returns > 0, the object is True
__bool__ key points:
- Returns boolean — True or False
- Called in if statements — when object is used in a condition
- Called by bool() — built-in bool() function
- Fallback to __len__ — if __bool__ is not defined, Python uses __len__
- Defines what's "truthy" — when the object is considered True
Quick Check: What does __bool__ return? (Answer: True or False)
__str__ vs __repr__
Understanding When to Use Each
One of the most common questions about special methods is the difference between __str__ and __repr__. Let's look at them side by side to understand when to use each.
# __str__ vs __repr__ - A detailed comparison
class Product:
def __init__(self, name, price, category):
self.name = name
self.price = price
self.category = category
def __str__(self):
"""User-friendly representation"""
return f"{self.name} (${self.price:.2f}) - {self.category}"
def __repr__(self):
"""Developer-friendly representation"""
return f"Product('{self.name}', {self.price}, '{self.category}')"
# Creating a product
product = Product("Laptop", 999.99, "Electronics")
# __str__ - for users
print(product) # Laptop ($999.99) - Electronics
print(str(product)) # Laptop ($999.99) - Electronics
print(f"Product: {product}") # Product: Laptop ($999.99) - Electronics
# __repr__ - for developers
print(repr(product)) # Product('Laptop', 999.99, 'Electronics')
# In the interactive shell, __repr__ is used
# product # Would show: Product('Laptop', 999.99, 'Electronics')
# Best practice: Always define __repr__
# And define __str__ when you want a user-friendly version
class Example:
def __init__(self, value):
self.value = value
def __repr__(self):
"""Always define __repr__ for debugging"""
return f"Example({self.value})"
# __str__ is optional but recommended
# When to use what:
# __str__: For display to users, printing, logging
# __repr__: For debugging, development, interactive work
# Both: Define __repr__ always, __str__ when needed
Comparison table:
- __str__ — user-friendly, readable, informal
- __repr__ — developer-friendly, unambiguous, formal
- __str__ — used by print(), str(), f-strings
- __repr__ — used by repr(), interactive shell, debugging
- __str__ — optional, fallback to __repr__
- __repr__ — always define this, it's recommended
Quick Check: Which method is used when you type an object name in the Python interactive shell? (Answer: __repr__)
Special Attributes
Built-in Attributes Every Class Has
Python classes come with several built-in attributes that provide information about the class and its objects. These attributes are always available and can be very useful.
# Built-in class attributes
class Student:
"""A class representing a student"""
school = "Python Academy"
def __init__(self, name, grade):
self.name = name
self.grade = grade
def get_info(self):
return f"{self.name} is in grade {self.grade}"
# 1. __name__ - The name of the class
print(f"Class name: {Student.__name__}") # Student
# 2. __doc__ - The class docstring
print(f"Docstring: {Student.__doc__}") # A class representing a student
# 3. __module__ - The module where the class is defined
print(f"Module: {Student.__module__}") # __main__
# 4. __dict__ - The class's dictionary of attributes
print(f"Attributes: {Student.__dict__}")
# 5. __class__ - The class of an object
alice = Student("Alice", 10)
print(f"Object's class: {alice.__class__}") #
# 6. __bases__ - The base classes of a class
print(f"Base classes: {Student.__bases__}") # (,)
# 7. __subclasses__() - Get all subclasses of a class
class GradStudent(Student):
pass
print(f"Subclasses: {Student.__subclasses__()}")
# 8. __mro__ - Method Resolution Order
print(f"MRO: {Student.__mro__}")
# 9. dir() - List all attributes and methods
print("All attributes:")
for attr in dir(Student):
if not attr.startswith('_'):
print(f" {attr}")
Special attributes summary:
- __name__ — the name of the class
- __doc__ — the class docstring
- __module__ — the module where the class is defined
- __dict__ — a dictionary of the class's attributes
- __class__ — the class of an object
- __bases__ — the base classes of a class
- __mro__ — Method Resolution Order
Quick Check: What attribute gives you the name of a class? (Answer: __name__)
Try It Yourself
Experiment with built-in class methods in the editor below.
BUILT-IN CLASS METHODS PRACTICE
========================================
1. __STR__ AND __REPR__
str: 'Inception' (2010)
repr: Movie('Inception', 2010)
2. __LEN__
Team size: 2
3. __CALL__
Hello, Alice!
Hi, Bob!
4. __BOOL__
Empty container is True? False
Non-empty container is True? True
Built-in class methods practice complete!
You've Got It!
You now understand Python's built-in class methods. You know how to use __str__, __repr__, __len__, __call__, __bool__, and more to make your classes more powerful.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between __str__ and __repr__?
Do I need to define both __str__ and __repr__?
What is the purpose of __call__?
What's a common interview question about built-in methods?
What happens if I don't define __str__?
<__main__.MyClass object at 0x...>.
What is the __dict__ attribute used for?
Where to Go From Here
Now that you understand built-in class methods, check out these related topics:
Class and Instance Variables
Learn the difference between class and instance variables.
Learn More →Inheritance
Learn how to create class hierarchies with inheritance.
Learn More →Method Overriding
Learn how to override methods in subclasses.
Learn More →