
Methods in Python
What is a Method in Python?
A method is a function that belongs to an object or a class. It is used to perform a specific task.
For example:
class Student:
def greet(self):
print("hello,iam sathwik")
student=Student()
student.greet()
Output
hello,iam sathwik
Here, greet() is a method because it is defined inside the Student class.
Types of Methods in Python
When working with classes, Python mainly has three types of methods:
- Instance Method
- Class Method
- Static Method
1. Instance Method
An instance method works with an object of a class. It normally uses self as its first parameter.
class Student:
def display(self):
print("My name is Sathwik")
s1 = Student()
s1.display()
Output:
My name is Sathwik
Here, display() is an instance method. We call it using the object s1.
2. Class Method
A class method works with the class rather than a particular object. It uses the @classmethod decorator and cls as its first parameter.
class Student:
college = "ABC College"
@classmethod
def show_college(cls):
print(cls.college)
Student.show_college()
Output:
ABC College
Here, show college() accesses the class variable college.
3. Static Method
A static method does not use self or cls. It is useful when we need a method that performs a task without using class or object data.
class Calculator:
@staticmethod
def add(a, b):
return a + b
print(Calculator.add(10, 20))
Output:
30
Here, add() simply adds two numbers.
Join Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments