Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Built-in Class Methods and Attributes

Python Built-in Class Methods and Attributes - Complete Guide

Learn about Python's special methods that make your classes more powerful and intuitive.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What are Built-in Class Methods?
  • __str__ — String Representation
  • __repr__ — Developer Representation
  • __len__ — Length of Objects
  • __call__ — Making Objects Callable
  • __bool__ — Truth Value
  • __str__ vs __repr__
  • Special Attributes
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • 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

1

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

2

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

3

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

4

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

5

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__

6

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

7

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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:

1. What does __str__ do?
2. What is the difference between __str__ and __repr__?
3. What does __len__ return?
4. What does __call__ do?
5. What is the purpose of __bool__?

Frequently Asked Questions

What is the difference between __str__ and __repr__? ▼

__str__ is for users — it should be readable and friendly. __repr__ is for developers — it should be unambiguous and ideally show how to recreate the object. __str__ is used by print() and str(), while __repr__ is used by the interactive shell and repr().

Do I need to define both __str__ and __repr__? ▼

You should always define __repr__ — it's the recommended practice. __str__ is optional. If you don't define __str__, Python will use __repr__ as a fallback. For most classes, it's good to define both.

What is the purpose of __call__? ▼

The __call__ method makes your object callable like a function. This is useful for creating objects that maintain state while behaving like functions. It's commonly used in decorators, counters, and factory functions.

What's a common interview question about built-in methods? ▼

Common questions include: "What is the difference between __str__ and __repr__?" "What does __call__ do?" "Explain the purpose of __len__" and "What are special methods in Python?"

What happens if I don't define __str__? ▼

If you don't define __str__, Python will use the __repr__ method as a fallback. If __repr__ is also not defined, Python will use the default representation from the object class, which looks like <__main__.MyClass object at 0x...>.

What is the __dict__ attribute used for? ▼

__dict__ is a dictionary that stores the attributes of an object or class. For objects, it contains all instance attributes. For classes, it contains all class attributes and methods. It's useful for introspection and debugging.

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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: Destructor Next: Class and Instance Variables →