n Object-Oriented Programming (OOP), a method is a function that is defined inside a class.
Methods define the behavior of an object.
If variables represent the data of an object, methods represent the actions of that object.
Basic Syntax
class ClassName:
def method_name(self):
# code block
self refers to the current object that is calling the method.
Example of a Simple Method
class Student:
def greet(self):
print("Hello Student")s1 = Student()
s1.greet()
Output:
Hello Student
Here:
greet()is a method- It is called using the object
s1
Method with Parameters
Methods can also accept additional parameters.
class Student:
def greet(self, name):
print("Hello", name)s1 = Student()
s1.greet("Hira")
Output:
Hello Hira
Types of Methods in Python
There are mainly three types of methods:
1. Instance Methods
- Work with instance variables
- Must use
self - Called using object
class Student:
def __init__(self, name):
self.name = name def display(self):
print(self.name)s1 = Student("Hira")
s1.display()
2. Class Methods
- Work with class variables
- Use
@classmethoddecorator - Use
clsinstead ofself
class Student:
school = "GIGZ Academy" @classmethod
def show_school(cls):
print(cls.school)Student.show_school()
3. Static Methods
- Do not use instance or class variables
- Use
@staticmethoddecorator - No
selforcls
class Math:
@staticmethod
def add(a, b):
return a + bprint(Math.add(5, 3))
Difference Between Method Types
Instance Method
Uses object data
Requires self
Called using object
Class Method
Uses class data
Requires cls
Called using class
Static Method
Does not use class or object data
No self or cls
Called using class
Key Takeaway
Methods define what an object can do.
They help organize code inside classes and make programs structured, reusable, and easy to manage.