Working with Instance, Class, and Static Methods in Python
Course: Python Programming Training
Topic: Working with Instance, Class, and Static Methods
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Course Demo
Official Website: JustAcademy Homepage
1. Introduction to Methods in Python
Python supports object-oriented programming (OOP), which allows developers to organize code using classes and objects. A class defines the structure and behavior of objects, while an object is an instance of a class.
Methods are functions defined inside a class. They represent the actions that objects or classes can perform. Python commonly uses three types of methods:
- Instance methods: Work with the data of a particular object.
- Class methods: Work with class-level data and receive the class itself as the first argument.
- Static methods: Provide related utility functionality without automatically receiving an instance or class as the first argument.
Understanding these methods helps developers decide where a particular operation belongs, avoid unnecessary dependencies, and create reusable, maintainable code.
2. Learning Objectives
After studying this topic, you will be able to:
- Understand methods and their role in Python classes.
- Define and call instance methods using
self.
- Define class methods using the
@classmethod decorator.
- Understand the purpose of the
cls parameter.
- Define static methods using the
@staticmethod decorator.
- Distinguish between instance, class, and static methods.
- Use all three method types in practical programs.
- Identify common errors and follow Python coding best practices.
3. Understanding Classes, Objects, and Methods
3.1 What Is a Class?
A class is a blueprint for creating objects. It can contain attributes, which represent data, and methods, which represent behavior.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print(f"Name: {self.name}")
print(f"Marks: {self.marks}")
student1 = Student("Aarav", 85)
student1.display()
Output:
Name: Aarav
Marks: 85
In this example, Student is the class, student1 is an object, and display() is an instance method.
3.2 What Is an Object?
An object is a specific instance created from a class. Each object can have its own instance attributes.
student1 = Student("Aarav", 85)
student2 = Student("Diya", 92)
print(student1.name)
print(student2.name)
Output:
Aarav
Diya
Both objects belong to the same class, but their names and marks are stored separately.
3.3 What Is a Method?
A method is a function associated with a class. Methods can operate on instance data, class data, or perform utility operations that do not require either.
For example, a banking application might use:
- An instance method to deposit money into a particular account.
- A class method to manage a setting shared by all accounts of a class.
- A static method to validate an account number's format.
4. Instance Methods in Python
4.1 Definition of an Instance Method
An instance method is a method that operates on a particular object. It is the most common method type in Python classes and is defined without a special decorator.
The first parameter is conventionally named self. When an instance method is called through an object, Python automatically passes that object as the first argument.
4.2 Understanding the self Parameter
The self parameter refers to the current instance. It allows a method to read or modify the attributes belonging to that object.
self is a naming convention rather than a reserved Python keyword. However, using this conventional name makes code easier to understand.
4.3 Creating an Instance Method
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display_details(self):
print(f"Employee: {self.name}")
print(f"Salary: {self.salary}")
employee1 = Employee("Riya", 45000)
employee1.display_details()
Output:
Employee: Riya
Salary: 45000
Explanation:
__init__() initializes the object's attributes.
self.name stores the employee's name.
self.salary stores the employee's salary.
display_details() accesses the attributes of the current object.
4.4 Modifying Instance Attributes
Instance methods can update the data of the object on which they are called.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposit successful. Balance: {self.balance}")
else:
print("Amount must be positive.")
account1 = BankAccount("Aman", 1000)
account1.deposit(500)
Output:
Deposit successful. Balance: 1500
The method updates account1's balance. If another account object exists, its balance remains unchanged unless its own data is modified.
4.5 Calling Instance Methods
Instance methods are normally called through an object.
class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
print(calc.add(10, 20))
Output:
30
Python automatically supplies calc as the self argument. The call is conceptually equivalent to Calculator.add(calc, 10, 20).
4.6 When Should You Use Instance Methods?
Use instance methods when an operation depends on an object's individual data or needs to update that data.
- Updating a student's marks.
- Changing a user's profile information.
- Depositing or withdrawing money from an account.
- Calculating the total price of a particular shopping cart.
- Updating the status of an individual order.
5. Class Methods in Python
5.1 Definition of a Class Method
A class method operates in the context of a class rather than being automatically bound to a particular instance. It is defined with the @classmethod decorator.
Its first parameter is conventionally named cls, which refers to the class receiving the method call. A class method can access or modify class attributes through cls.
5.2 Understanding the @classmethod Decorator
The @classmethod decorator changes how Python binds the method. When called through the class or an instance, Python supplies the relevant class as the first argument.
class Employee:
company_name = "Tech Solutions"
@classmethod
def display_company(cls):
print(f"Company: {cls.company_name}")
Employee.display_company()
Output:
Company: Tech Solutions
Here, cls.company_name accesses the class attribute. An instance is not required to call this method.
5.3 Understanding the cls Parameter
The name cls is a convention similar to self. It represents the class object rather than a particular instance.
class Product:
category = "General"
@classmethod
def show_category(cls):
return cls.category
print(Product.show_category())
Output:
General
Using cls is preferable to hard-coding the class name because the method can work appropriately with subclasses.
5.4 Modifying Class Attributes
A class method can update a class-level attribute. The change is visible through the class and instances that inherit or otherwise resolve that attribute from the class.
class Employee:
company_name = "Tech Solutions"
@classmethod
def change_company(cls, new_name):
cls.company_name = new_name
Employee.change_company("NextGen Technologies")
print(Employee.company_name)
Output:
NextGen Technologies
Important: Assigning through cls normally changes the attribute on the class represented by cls. If a subclass calls the method, the assignment may create or update an attribute on that subclass rather than the parent class.
5.5 Class Methods as Alternative Constructors
One of the most useful applications of class methods is creating alternative constructors. These methods provide additional ways to create objects from different kinds of input.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
@classmethod
def from_string(cls, student_data):
name, marks = student_data.split(",")
return cls(name.strip(), int(marks.strip()))
student = Student.from_string("Meera, 91")
print(student.name)
print(student.marks)
Output:
Meera
91
Explanation:
from_string() accepts a comma-separated string.
split(",") separates the name and marks.
strip() removes surrounding whitespace.
int() converts marks to an integer.
cls(...) creates an object using the receiving class.
Using cls instead of explicitly writing Student(...) supports inheritance more effectively because subclasses can reuse the alternative constructor.
5.6 When Should You Use Class Methods?
- Creating objects from strings, dictionaries, or other input formats.
- Managing class-level configuration.
- Maintaining class-wide counters or settings.
- Implementing alternative constructors.
- Writing behavior that should adapt to the class or subclass receiving the call.
6. Static Methods in Python
6.1 Definition of a Static Method
A static method is a function placed inside a class because it is logically related to that class. It is defined using the @staticmethod decorator.
Unlike an instance method or class method, a static method does not automatically receive self or cls. It accepts only the arguments explicitly provided by the caller.
6.2 Understanding the @staticmethod Decorator
The @staticmethod decorator allows a method to be called through the class or an instance without automatic instance or class binding.
class Calculator:
@staticmethod
def add(a, b):
return a + b
print(Calculator.add(10, 20))
calc = Calculator()
print(calc.add(5, 7))
Output:
30
12
The static method performs a calculation without accessing any instance attributes or class attributes.
6.3 Static Method for Validation
Static methods are useful for validation and utility operations related to a class.
class User:
@staticmethod
def is_valid_age(age):
return isinstance(age, int) and not isinstance(age, bool) and 18 <= age <= 100
print(User.is_valid_age(25))
print(User.is_valid_age(15))
print(User.is_valid_age(120))
Output:
True
False
False
This method validates an age without needing information about a particular user. The explicit Boolean exclusion prevents values such as True from being treated as valid integer ages.
6.4 Static Method for Formatting Data
class TextUtility:
@staticmethod
def make_title(text):
return text.strip().title()
print(TextUtility.make_title(" python programming "))
Output:
Python Programming
The method uses only the input argument, so it does not need an instance or class parameter.
6.5 When Should You Use Static Methods?
- Validating input values.
- Converting or formatting data.
- Performing calculations independent of object state.
- Grouping related helper functions inside a class.
- Checking whether a value meets a business rule that does not require instance or class data.
If a utility function has no meaningful relationship to the class, a regular module-level function may be a clearer choice than a static method.
7. Difference Between Instance, Class, and Static Methods
| Feature |
Instance Method |
Class Method |
Static Method |
| Decorator |
None required |
@classmethod |
@staticmethod |
| First parameter |
self by convention |
cls by convention |
No automatic first parameter |
| Receives instance automatically |
Yes, when called through an instance |
No |
No |
| Receives class automatically |
Not as a dedicated parameter; it can access the class through the instance |
Yes |
No |
| Accesses instance data |
Yes, through self |
Not automatically; no instance is supplied |
Not automatically |
| Accesses class data |
Can access it through the instance or class |
Yes, through cls |
Only if explicitly referenced or passed |
| Typical purpose |
Object-specific behavior |
Class-level behavior and alternative constructors |
Related utility functionality |
| Called through class |
Requires the instance as an explicit argument when called directly through the class |
Yes |
Yes |
| Called through instance |
Yes |
Yes |
Yes |
7.1 Simple Way to Remember
- Instance method: Uses
self and focuses on one object.
- Class method: Uses
cls and focuses on the class.
- Static method: Uses neither automatically and focuses on a related independent operation.
8. Using All Three Methods in One Class
The following example combines instance, class, and static methods in a single employee-management class.
class Employee:
company_name = "Bright Future Ltd."
employee_count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
type(self).employee_count += 1
# Instance method
def display_details(self):
print(f"Name: {self.name}")
print(f"Salary: {self.salary}")
print(f"Company: {self.company_name}")
# Class method
@classmethod
def change_company(cls, new_name):
cls.company_name = new_name
# Static method
@staticmethod
def is_valid_salary(salary):
return isinstance(salary, (int, float)) and not isinstance(salary, bool) and salary >= 0
employee1 = Employee("Asha", 40000)
employee1.display_details()
Employee.change_company("Future Tech Ltd.")
print(Employee.company_name)
print(Employee.is_valid_salary(35000))
print(Employee.is_valid_salary(-100))
Output:
Name: Asha
Salary: 40000
Company: Bright Future Ltd.
Future Tech Ltd.
True
False
Explanation:
display_details() uses the current employee's instance data.
change_company() updates a class-level company name.
is_valid_salary() checks an input value without relying on employee state.
employee_count demonstrates a class attribute used to track created employees.
Design note: Class-level counters and settings need deliberate handling when subclasses are involved. For a simple example, this pattern illustrates class data; larger applications may need a carefully designed counting or registration strategy.
9. Practical Example: Student Management System
This example demonstrates all three method types in a more realistic scenario.
class Student:
school_name = "Knowledge Academy"
def __init__(self, name, marks):
self.name = name
self.marks = marks
# Instance method
def display(self):
print(f"Student: {self.name}")
print(f"Marks: {self.marks}")
print(f"School: {self.school_name}")
# Instance method
def update_marks(self, new_marks):
if self.is_valid_marks(new_marks):
self.marks = new_marks
return True
return False
# Class method
@classmethod
def change_school(cls, new_name):
cls.school_name = new_name
# Class method as an alternative constructor
@classmethod
def from_string(cls, record):
name, marks = record.split(",")
return cls(name.strip(), int(marks.strip()))
# Static method
@staticmethod
def is_valid_marks(marks):
return isinstance(marks, (int, float)) and not isinstance(marks, bool) and 0 <= marks <= 100
student1 = Student("Kabir", 78)
student1.update_marks(88)
student1.display()
student2 = Student.from_string("Anaya, 94")
student2.display()
Student.change_school("Future Learning Center")
student1.display()
Output:
Student: Kabir
Marks: 88
School: Knowledge Academy
Student: Anaya
Marks: 94
School: Knowledge Academy
Student: Kabir
Marks: 88
School: Future Learning Center
What this example teaches:
- Each student has independent name and marks attributes.
- The instance method updates one student's marks.
- The class method provides an alternative way to create a student object.
- The static method checks whether marks are within the permitted range.
- The class method updates the school name stored on the class.
Because the school name is accessed through self.school_name and the class attribute is changed through Student.change_school(), the existing students see the updated value unless an instance has its own attribute named school_name.
10. Understanding Method Binding
Method binding describes how Python supplies the first argument when a method is accessed and called.
10.1 Instance Method Binding
class Demo:
def show(self, message):
print(message)
obj = Demo()
obj.show("Hello")
Python automatically supplies obj as self. The call is conceptually equivalent to Demo.show(obj, "Hello").
10.2 Class Method Binding
class Demo:
@classmethod
def show_class(cls):
print(cls.__name__)
Demo.show_class()
Output:
Demo
Python supplies the class as cls.
10.3 Static Method Binding
class Demo:
@staticmethod
def show_message(message):
print(message)
Demo.show_message("Welcome to Python")
Output:
Welcome to Python
No instance or class is automatically passed to the static method.
11. Inheritance and Method Types
Inheritance allows a child class to reuse behavior from a parent class. Class methods are particularly useful when their behavior should adapt to the subclass receiving the call.
class Person:
role = "Person"
@classmethod
def get_role(cls):
return cls.role
class Teacher(Person):
role = "Teacher"
print(Person.get_role())
print(Teacher.get_role())
Output:
Person
Teacher
The class method receives Person when called through Person and Teacher when called through Teacher. This behavior makes cls useful in inherited class methods.
11.1 Instance Methods in Inheritance
class Animal:
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Bark"
dog = Dog()
print(dog.speak())
Output:
Bark
The child class overrides the inherited instance method.
11.2 Static Methods in Inheritance
Static methods can also be inherited and called through a subclass. However, they do not automatically receive the subclass as an argument. If the behavior must adapt to the receiving class, a class method may be a better fit.
12. Common Errors and Troubleshooting
| Error or Problem |
Cause |
Solution |
Missing self argument |
An instance method was called through the class without passing an instance. |
Call it through an object or explicitly provide the instance. |
Missing cls argument |
A method was intended to be a class method but was not decorated correctly or was defined incorrectly. |
Use @classmethod and accept cls as the first parameter. |
| Unexpected argument in static method |
The code expects Python to pass self or cls automatically. |
Remember that static methods receive only explicitly supplied arguments. |
| Class attribute does not update as expected |
An instance attribute may be shadowing a class attribute, or the method may update a different class. |
Inspect attribute access and use cls or the intended class consistently. |
| Incorrect decorator |
@staticmethod or @classmethod is missing or placed incorrectly. |
Place the appropriate decorator immediately above the method definition. |
| Invalid data accepted |
A method performs an incomplete validation check. |
Validate type, range, and edge cases explicitly. |
| Using a static method for object updates |
The operation requires data from a particular instance. |
Use an instance method when the behavior depends on self. |
12.1 Error Example: Missing self
class Test:
def show(self):
print("Hello")
Test.show()
Typical result: Python raises a TypeError because the required instance argument is missing.
Corrected version:
class Test:
def show(self):
print("Hello")
obj = Test()
obj.show()
Output:
Hello
12.2 Error Example: Incorrect Static Method Definition
class Calculator:
@staticmethod
def add(self, a, b):
return a + b
print(Calculator.add(2, 3))
This definition is confusing because self is not automatically supplied to a static method. The call above supplies only two arguments, while the function expects three.
Corrected version:
class Calculator:
@staticmethod
def add(a, b):
return a + b
print(Calculator.add(2, 3))
Output:
5
13. Best Practices
- Use instance methods for operations that read or modify individual object data.
- Use class methods for behavior involving class-level data or alternative object construction.
- Use static methods for related utility functions that do not need automatic access to instance or class state.
- Follow the conventional parameter names
self and cls.
- Choose descriptive method names, such as
update_salary(), from_dict(), and is_valid_email().
- Keep methods focused on one responsibility.
- Validate external inputs when required instead of assuming that arguments always have the correct type or value.
- Avoid changing class-level data unnecessarily, because the change may affect multiple objects.
- Use class methods for alternative constructors when the class itself determines which object should be created.
- Do not add a static method merely to avoid creating an object; use a regular function if the behavior is unrelated to the class.
- Write docstrings for methods whose purpose, arguments, or return values may not be obvious.
- Test inherited behavior when using class methods in a class hierarchy.
14. Practice Exercises
Exercise 1: Instance Method
Create a Book class with attributes title and author. Write an instance method called display_info() to display the details of a book.
Exercise 2: Class Method
Create a Company class with a class attribute called company_name. Write a class method called change_name() that updates the company name.
Exercise 3: Static Method
Create a Temperature class with a static method called celsius_to_fahrenheit(celsius). Use the formula (celsius * 9 / 5) + 32 to convert a temperature.
Exercise 4: Alternative Constructor
Create a Product class with name and price attributes. Implement a class method called from_string() that creates an object from a string such as "Laptop, 55000".
Exercise 5: Combined Application
Create a BankAccount class that includes:
- An instance method to deposit money.
- An instance method to withdraw money.
- A class method to update a class-level bank name.
- A static method to check whether a transaction amount is positive.
Test the program with multiple account objects and verify that each method behaves as expected.
15. Mini Project: Employee Management System
Project objective: Build a small employee-management program that uses all three method types appropriately.
Requirements:
- Create an
Employee class with employee name, salary, and department.
- Implement an instance method to display employee details.
- Implement an instance method to update an employee's salary after validating the amount.
- Implement a class method to update the company name.
- Implement a class method to create an employee from a dictionary.
- Implement a static method to check whether a salary is valid.
- Create at least three employee objects and test the methods.
Sample implementation:
class Employee:
company_name = "ABC Technologies"
def __init__(self, name, salary, department):
self.name = name
self.salary = salary
self.department = department
def display(self):
print(f"Name: {self.name}")
print(f"Salary: {self.salary}")
print(f"Department: {self.department}")
print(f"Company: {self.company_name}")
def update_salary(self, new_salary):
if self.is_valid_salary(new_salary):
self.salary = new_salary
return True
return False
@classmethod
def change_company(cls, name):
cls.company_name = name
@classmethod
def from_dict(cls, data):
return cls(
data["name"],
data["salary"],
data["department"]
)
@staticmethod
def is_valid_salary(salary):
return (
isinstance(salary, (int, float))
and not isinstance(salary, bool)
and salary >= 0
)
employee1 = Employee("Neha", 40000, "IT")
employee2 = Employee.from_dict({
"name": "Rahul",
"salary": 50000,
"department": "Sales"
})
employee1.update_salary(45000)
Employee.change_company("NextGen Solutions")
employee1.display()
employee2.display()
Expected learning outcome: The project demonstrates how instance methods manage individual employee records, class methods provide class-level operations and alternative construction, and static methods perform independent validation.
16. Interview Questions and Answers
Q1. What is an instance method in Python?
An instance method is a method that operates on a particular object. It conventionally accepts self as its first parameter and can access or modify the object's attributes.
Q2. What does self represent?
self refers to the current object on which an instance method is called. It is a naming convention, not a reserved keyword.
Q3. What is a class method?
A class method is defined using @classmethod and receives the class as its first argument, conventionally named cls.
Q4. What is the purpose of the cls parameter?
cls refers to the class receiving the method call. It is commonly used to access class attributes and construct instances in a way that supports subclasses.
Q5. What is a static method?
A static method is defined using @staticmethod. It does not automatically receive an instance or class as its first argument.
Q6. Can a static method be called without creating an object?
Yes. A static method can be called directly through the class, for example, Calculator.add(2, 3).
Q7. Can a class method be called through an instance?
Yes. A class method can be called through either the class or an instance. In both cases, the receiving class is passed as the first argument.
Q8. Can an instance method access class attributes?
Yes. An instance method can access class attributes through self or the class itself. Care is needed because an instance attribute can shadow a class attribute with the same name.
Q9. Why are class methods useful as alternative constructors?
They allow objects to be created from different input formats, such as strings or dictionaries. Using cls allows the constructor to work with subclasses.
Q10. What is the main difference between class and static methods?
A class method automatically receives the class as cls, while a static method receives no automatic instance or class argument.
Q11. Which method should be used to update one object's balance?
An instance method is usually appropriate because the operation depends on the balance of a particular account.
Q12. Which method is appropriate for validating an independent input value?
A static method can be appropriate when the validation is logically related to the class but does not need instance or class state. A module-level function may also be suitable.
Q13. Does a class method automatically modify every subclass and parent class attribute?
No. Assigning through cls updates the attribute on the class represented by cls. Inheritance and attribute lookup determine what other classes observe.
Q14. What happens if an instance method is called through a class without passing an instance?
Python generally raises a TypeError because the required first argument has not been provided.
Q15. Can all three method types exist in one class?
Yes. A class can contain instance methods, class methods, and static methods, each serving a different responsibility.
17. Quick Revision Checklist
- Instance methods are defined without a special decorator and conventionally use
self.
- Instance methods are suitable for object-specific behavior.
- Class methods use the
@classmethod decorator and conventionally accept cls.
- Class methods are useful for class-level operations and alternative constructors.
- Static methods use the
@staticmethod decorator.
- Static methods do not automatically receive
self or cls.
- Methods should be selected based on the data and behavior they need.
- Class-level changes can affect how multiple instances access shared attributes.
- Test method behavior through both class and instance calls where appropriate.
18. Conclusion
Instance, class, and static methods are important building blocks of Python object-oriented programming. Instance methods handle the behavior and data of individual objects, class methods handle behavior associated with the class and support alternative constructors, and static methods organize useful operations that do not need automatic access to instance or class state.
Choosing the correct method type makes programs easier to read, test, extend, and maintain. Practicing with student, employee, product, and bank-account examples will help you understand how these methods work in real applications.
To continue learning Python programming, explore the Python Training Course, visit the JustAcademy website, or register for a course demo.