Python Methods
Table of Contents
Description
Method: A function defined inside a class that operates on objects (instances) of that class.
Methods are used to define the behavior of objects and manipulate instance/class data.
Types of Methods:
Instance Methods – Operate on instance data via self
Class Methods – Work with class-level data via cls
Static Methods – Behave like regular functions but live inside class namespaces
Dunder (Magic) Methods – Special methods with __double_underscores__ used for operator overloading, etc.
Prerequisites
- Understanding of classes and objects
- Basics of Python functions and the self keyword
- Knowledge of variable scopes (instance vs class)
Examples
Here's a simple program in Python:
✅ Basic Instance Method class Student: def __init__(self, name): self.name = name # Instance variable # Instance method def greet(self): print(f"Hello, {self.name}!") s1 = Student("Alice") s1.greet() # Output: Hello, Alice! ✅ Class Method class Student: school = "ABC High School" def __init__(self, name): self.name = name @classmethod def change_school(cls, new_name): cls.school = new_name # Class variable changed Student.change_school("XYZ Public School") print(Student.school) # Output: XYZ Public School ✅ Static Method class Math: @staticmethod def add(a, b): return a + b # No access to class or instance print(Math.add(10, 5)) # Output: 15 ✅ Magic Method (Dunder Method) – __str__ class Book: def __init__(self, title): self.title = title # Magic method to return a readable string def __str__(self): return f"Book Title: {self.title}" b = Book("Python Essentials") print(b) # Output: Book Title: Python Essentials ✅ Operator Overloading with __add__ class Vector: def __init__(self, x, y): self.x = x self.y = y # Overload + operator def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __str__(self): return f"({self.x}, {self.y})" v1 = Vector(1, 2) v2 = Vector(3, 4) v3 = v1 + v2 print(v3) # Output: (4, 6)Real-World Applications
Instance Methods for user profile updates, booking actions, and order management
Class Methods to track shared resources like number of users, changing global settings.
Static Methods for utility functions like date/time formatting, calculations
Magic Methods to customize class behavior in APIs, frameworks, and libraries
Where topic Can Be Applied
Web development: Request handling, object validation (e.g., Django models)
Data analysis tools: Data transformation via methods
Frameworks/libraries: Use of magic methods like __getitem__, __call__, __len__
Games: Actions like move(), attack(), defend()
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What is the difference between instance, class, and static methods?
When should you use a static method?
What is the purpose of the __str__ method?
How does operator overloading work in Python?
Can static methods access instance or class variables?