Python Class Methods
Class Methods
Methods are functions defined inside a class. While properties describe what an object has, methods describe what an object does — a BankAccount can deposit(), a TaskList can add_task(), and a User can say_hello().
Most methods are instance methods: they work with a specific object and automatically receive that object through the self parameter.
Terminology note: In everyday speech, "class methods" often means "methods in a class", which is how this lesson begins. In Python, however, class method also has a precise meaning: a method marked with
@classmethodthat works with the class rather than an individual object. Both are covered here, along with@staticmethod.
Defining a Method in a Class
Methods are written just like functions, but they are indented inside a class, and their first parameter is self.
Example: A Simple Method
class User:
def __init__(self, username):
self.username = username
def say_hello(self):
print(f"Hi, I am {self.username}")
u1 = User("Ananya")
u1.say_hello()
Expected output:
Hi, I am Ananya
What happens:
u1.say_hello()calls the method on the objectu1.- Python automatically passes
u1asself. self.usernamereads theusernamestored onu1.
Note:
selfmust always be the first parameter of an instance method. You do not pass it yourself when calling the method.
Methods vs Functions
| Function | Method | |
|---|---|---|
| Defined | At the top level of a module | Inside a class |
| Called with | function_name(args) | object.method_name(args) |
| First parameter | Whatever the function needs | self — the object (for instance methods) |
| Can access object data | Only if passed in | Directly through self |
Methods With Parameters
Methods can accept additional parameters after self, just like normal functions.
Example: Methods With Arguments
class MathTool:
def subtract(self, x, y):
return x - y
def power(self, base, exp):
return base ** exp
tool = MathTool()
print(tool.subtract(10, 4))
print(tool.power(2, 5))
Expected output:
6
32
When calling tool.subtract(10, 4), Python passes tool as self, 10 as x, and 4 as y.
These two methods never use self, because they do not need any object data. Methods like this are good candidates for @staticmethod, covered later in this lesson.
Methods That Read Object Properties
Methods can read an object's data through self.
Example: Accessing Properties Inside a Method
class Profile:
def __init__(self, name, country):
self.name = name
self.country = country
def details(self):
return f"{self.name} lives in {self.country}"
p1 = Profile("Riya", "India")
print(p1.details())
Expected output:
Riya lives in India
details() returns a string instead of printing it, so the caller can decide what to do with the result — print it, save it, or combine it with other text.
Methods That Modify Object Properties
Methods can also update an object's properties.
Example: Modifying a Property
class Counter:
def __init__(self, value=0):
self.value = value
def increment(self):
self.value += 1
print(f"Current value: {self.value}")
c1 = Counter()
c1.increment()
c1.increment()
Expected output:
Current value: 1
Current value: 2
Each call to increment() changes self.value on c1. The object remembers its state between method calls — this is one of the main advantages of objects over plain functions.
The str() Method
__str__() is a special method that defines what is displayed when an object is printed or converted to a string with str().
Without str()
class Device:
def __init__(self, name):
self.name = name
d1 = Device("Router")
print(d1)
Example output (the address will differ):
<__main__.Device object at 0x7f9a1c2b3d90>
Python's default display shows the class name and memory address, which is rarely useful.
With str()
class Device:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Device Name: {self.name}"
d1 = Device("Router")
print(d1)
Expected output:
Device Name: Router
print() now calls d1.__str__() automatically and displays the string it returns. Note that __str__() must return a string — not print it.
Methods with double underscores on both sides, such as __init__() and __str__(), are called special methods or dunder methods. Python calls them automatically in specific situations.
Multiple Methods Working Together
A class usually contains several methods that cooperate to manage the object's data.
Example: A To-Do List
class TaskList:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append(task)
print(f"Task added: {task}")
def remove_task(self, task):
if task in self.tasks:
self.tasks.remove(task)
print(f"Task removed: {task}")
else:
print(f"Task not found: {task}")
def show_tasks(self):
print("Tasks:")
for t in self.tasks:
print("-", t)
todo = TaskList()
todo.add_task("Study Python")
todo.add_task("Practice OOP")
todo.remove_task("Go shopping")
todo.show_tasks()
Expected output:
Task added: Study Python
Task added: Practice OOP
Task not found: Go shopping
Tasks:
- Study Python
- Practice OOP
How the class is designed:
__init__()creates an empty list for eachTaskListobject.add_task(),remove_task(), andshow_tasks()all work with the sameself.taskslist.remove_task()checks that the task exists before removing it, avoiding aValueError.
Code outside the class does not need to know that tasks are stored in a list — it just calls the methods.
Class Methods With @classmethod
A class method is bound to the class, not to an individual object. It is marked with the @classmethod decorator, and its first parameter is conventionally named cls, which receives the class itself.
Class methods are used to work with class-level data, or to provide alternative ways of creating objects.
Example: An Alternative Constructor
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def from_string(cls, data):
name, salary = data.split(",")
return cls(name, int(salary))
e1 = Employee.from_string("Anita,75000")
print(e1.name, e1.salary)
Expected output:
Anita 75000
from_string()is called on the class:Employee.from_string(...).clsis theEmployeeclass, socls(name, int(salary))creates a newEmployee.- This gives a convenient way to build objects from text, such as a line in a CSV file.
Example: Working With Class Data
class Order:
count = 0
def __init__(self, item):
self.item = item
Order.count += 1
@classmethod
def total_orders(cls):
return f"Total orders: {cls.count}"
Order("Pen")
Order("Book")
print(Order.total_orders())
Expected output:
Total orders: 2
Static Methods With @staticmethod
A static method receives neither self nor cls. It is a regular function placed inside a class because it is logically related to it. Mark it with @staticmethod.
class MathTool:
@staticmethod
def subtract(x, y):
return x - y
print(MathTool.subtract(10, 4))
Expected output:
6
The method can be called on the class without creating an object. This is a cleaner version of the MathTool example earlier, whose methods never used self.
Comparing the Three Method Types
| Type | Decorator | First Parameter | Can Access | Typical Use |
|---|---|---|---|---|
| Instance method | None | self (the object) | Object data and class data | Most methods |
| Class method | @classmethod | cls (the class) | Class data | Alternative constructors, class-wide counters |
| Static method | @staticmethod | None | Neither (only its arguments) | Utility functions related to the class |
Deleting Methods From a Class
A method can be removed from a class with del. Because methods belong to the class, this affects all objects of that class — including ones that already exist.
Example: Deleting a Method
class Demo:
def show(self):
print("Hello")
obj = Demo()
obj.show()
del Demo.show
obj.show()
Output:
Hello
AttributeError: 'Demo' object has no attribute 'show'
The first call works; after del Demo.show, the method no longer exists. Deleting methods is very rarely done in real programs.
Common Mistakes
| Mistake | Problem |
|---|---|
Forgetting self in an instance method | TypeError: takes 0 positional arguments but 1 was given |
Forgetting the parentheses: u1.say_hello | Refers to the method without calling it |
__str__() printing instead of returning | TypeError: __str__ returned non-string |
Calling another method without self. | NameError |
Calling an instance method on the class: User.say_hello() | TypeError — it needs an object |
Related Concepts
- Python self Parameter — how instance methods access their object
- Python Class Properties — the data methods work with
- Python Functions — decorators, parameters, and return values
- Python Inheritance — reusing and overriding methods in subclasses