What are Methods in Python?

What are Methods in Python?

6 mins read864 Views Comment
Updated on Oct 3, 2023 11:57 IST

This blog explains Python Methods. We have explained this concept with the help of examples. Let’s explore!

2023_05_Copy-of-Copy-of-Feature-Image-Templates-40.jpg

Python is a versatile and strong programming language with a wide range of applications in several sectors. Python is also a Object-Oriented Progamming language which uses the classes and Objects. Python methods are functions that are associated with an object or a class in Python programming. They are used to perform specific tasks or operations on the data stored within objects or classes.

Explore Python Online Courses

Python methods has various uses:

  • Methods in Python are used to define the behaviour of the Python objects. 
  • Methods are used to improve the readability and maintainability of code.  
  • They help in breaking down complex tasks into smaller, more manageable tasks 

Now, let’s understand types of Python methods.

Table of Content

Types of Methods in Python 

In Python, there are three types of methods: instance, class, and static.  

  1. Instance methods are associated with an instance of a class and can modify the data stored within the instance.  
  2. Class methods are associated with the class rather than an instance and can access and modify class-level data.  
  3. Static methods are similar to functions outside of the class and cannot access any instance or class data.  
Understanding isnumeric() Method in Python
Understanding isnumeric() Method in Python
This blog will make you understand isnumeric() Method in Python. We have covered multiple examples here to explain you Python’s isnumeric() concept better. Let’s explore!This blog will make you understand...read more
What is Partition() Function in Python?
What is Partition() Function in Python?
This blog explains Partition() Function in Python with the help of example. Let’s understand! This blog explains Partition() Function in Python with the help of example. Let’s understand! This blog...read more
All About isdigit() Method in Python
All About isdigit() Method in Python
The isdigit() method in Python checks if all characters in a string are digits. It returns True if every character is a digit and False otherwise. This method is useful...read more
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

Instance Methods 

Characteristics: 

  • Instance methods are defined within the class definition and are called on an instance of the class using the dot notation. 
  • “Self” is often the first parameter of an instance method. 
  • They can access and modify the attributes of the instance on which they are called. 
  • They can also access and call other instance and class methods of the same class.  

Example: 

Here are some examples of instance methods: 

Example 1: Example to find the area of a circle using instance methods. 


 
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
circle1 = Circle(5)
print(circle1.area())
Copy code

Output: 

78.5 

Example 2: Creating a Car class to print the specifications of the particular car using instance methods. 


 
# Define the Car class
class Car:
# Initialize the Car object with the make, model, and year
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# Set the odometer reading to 0
self.odometer = 0
# Method to simulate driving the car and add to the odometer reading
def drive(self, miles):
self.odometer += miles
# Method to return the car's info including make, model, year, and
odometer reading
def get_info(self):
return f"{self.year} {self.make} {self.model} with {self.odometer} miles"
# Create an instance of the Car class with a make of "Toyota", model of
"Corolla", and year of 2022
my_car = Car("Toyota", "Corolla", 2022)
# Simulate driving the car for 50 miles
my_car.drive(50)
# Print the car's info
print(my_car.get_info())
Copy code

Output: 

2022 Toyota Corolla with 50 miles 

Advantages 

  • Instance methods allow for the encapsulation of behaviour specific to an instance of a class, improving code organisation and making it easier to manage complex code. 
  • Instance methods are inherited by subclasses, which makes it easy to reuse code and extend functionality. 
  • Instance methods are Python’s most commonly used method, and their purpose is straightforward to understand. 

Disadvantages

  • Each class instance contains a copy of all instance variables, which can be inefficient if the class has many instances. 
  • Instance methods are tightly coupled to the data stored within an instance, making it difficult to change the behaviour of a class without affecting other classes that use that class. 
  • Instance methods often rely on an instance’s state, making them difficult to test in isolation. 

Class Methods 

Class methods operate on the class itself rather than on an instance. Class methods are defined within the class definition and are called on the class rather than on an instance. 

Characteristics

  • Python class methods are associated with the class and are defined using the @classmethod decorator. 
  • They are conventionally named “cls” and have access to class-level data. 
  • Class methods are frequently used to create alternative constructors that allow for easier creation of class instances with attributes set differently. 
  • Class methods have access to class-level variables but not instance-level variables. However, because they are associated with the class, they are often used to modify class-level data. 

Examples of class methods 

Example 1: simple example illustrates the use of class methods 


 
import datetime
class Person:
# Define a class variable all_people as an empty list
all_people = []
# Define an instance method called __init__ that takes two arguments: name and age
def __init__(self, name, age):
self.name = name
self.age = age
# Add the instance to the all_people list
Person.all_people.append(self)
# Define a class method called from_birth_year that takes two arguments: cls and name and birth_year
@classmethod
def from_birth_year(cls, name, birth_year):
# Calculate the age based on the current year and birth year
age = datetime.date.today().year - birth_year
# Return a new instance of the Person class with the calculated age and given name
return cls(name, age)
# Create two instances of the Person class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Create a new instance of the Person class using the class method from_birth_year
person3 = Person.from_birth_year("Charlie", 1990)
# Print the names and ages of all people
for person in Person.all_people:
print(person.name, person.age)
Copy code

Output:

Alice 30
Bob 25
Charlie 33

Example 2: Employee class using class methods 


 
class Employee:
raise_amount = 1.05 # class variable
def __init__(self, first, last, salary):
self.first = first
self.last = last
self.salary = salary
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount # class method to set raise amount
emp1 = Employee("John", "Doe", 50000) # creating objects
emp2 = Employee("Jane", "Smith", 60000)
print(Employee.raise_amount)
Employee.set_raise_amount(1.10) # calling class method to set raise amount
print(Employee.raise_amount)
Copy code

Output: 

1.05 
1.10

Advantages

  • The advantages of class methods include that they can access and modify class-level data, which makes them useful for creating alternative constructors and performing operations that involve the class as a whole. 
  • They can be invoked on the class itself rather than an instance of the class, which means they can be called even if no class instances have been created. 
  • They can also improve code organization by grouping related functionality in the class definition. 

Disadvantages

  • Disadvantages of class methods include that they cannot access instance-level data, which may limit their usefulness in certain situations.  
  • They also require a clear understanding of class-level and instance-level data, which can make them more complex to work with. 
  • Overuse of class methods can also lead to tightly coupled code, which may make the code harder to maintain and test. 

Static Methods 

Static methods do not take the self or “cls” parameter and cannot access the instance, class variables, or methods. 

Characteristics

  • Static methods are independent of instances of the class and the class itself. They don’t take any implicit first parameter like self or cls. 
  • Static methods can’t access class-level data or instance-level data. They work like normal functions outside of the class and have no access to data except the data passed as arguments. 
  • To define a static method, you must use the @staticmethod decorator before the method definition. 
  • Static methods are often utilised for utility functions that don’t depend on any data of the class or instance. They can be used to perform calculations or operations related to the class but not dependent on it. 

Examples: 

Example 1: Static methods to add, multiply and find factorial of numbers. 


 
class MathOperations:
# Static method that adds two numbers
@staticmethod
def add_numbers(num1, num2):
return num1 + num2
# Static method that multiplies two numbers
@staticmethod
def multiply_numbers(num1, num2):
return num1 * num2
# Static method that computes the factorial of a number
@staticmethod
def factorial(num):
if num == 0:
return 1
else:
return num * MathOperations.factorial(num - 1)
# Example usage
print(MathOperations.add_numbers(2, 3))
print(MathOperations.multiply_numbers(4, 5))
print(MathOperations.factorial(4))
Copy code

Output: 

5
20
24

In this example, we have a MathOperations class with three static methods: add_numbers(), multiply_numbers(), and factorial(). 

  • The add_numbers() method takes two numbers as parameters and returns their sum.  
  • The multiply_numbers() method takes two numbers as parameters and returns their product. 
  • The n factorial() method takes a single number as a parameter and computes its factorial. 

Example 2: Static methods to add two numbers 


 
class Math:
# Define a static method named "add_numbers" that takes two parameters "x" and "y"
@staticmethod
def add_numbers(x, y):
# Returns the sum of the two numbers
return x + y
#Create an instance of the Math class and call the "add_numbers" method, passing in two arguments
print(Math.add_numbers(2, 3))
Copy code

Output: 

Note: All three methods are defined using the @staticmethod decorator, indicating that they are static. 

Advantages 

  • Static methods can execute operations independent of a specific instance or the class. 
  • They can be called without creating an instance of the class, making them more memory-efficient than instance methods in cases where only a specific functionality is required. 
  • They can be easily tested and mocked since they do not rely on the state of a specific instance or the class itself. 

Disadvantages

  • As static methods cannot access the instance or class, they cannot modify any instance or class-level data. 
  • They are less flexible than instance and class methods since they cannot be overridden in subclasses. 
  • They may not provide a clear separation between the functionality that should be part of the class and the functionality that standalone functions should provide. 

Comparison between Python Methods

  • Instance methods are bound to the instance of a class, and they can access and modify instance-level data. They are the most commonly used method type and are invoked on the class instance using dot notation. 
  • On the other hand, class methods are bound to the class itself, and they can access and modify class-level data. They are defined using the @classmethod decorator and are invoked on the class rather than the instance of the class. 
  • Static methods are not bound to the instance or the class and cannot access instance or class-level data. They are defined using the @staticmethod decorator and are used when the method doesn’t depend on the instance or class-level data. 
  • All three method types have access to class-level data and are defined using the same syntax. However, instance and class methods can access and modify instance-level and class-level data, respectively, while static methods do not. 
  • In terms of invocation, instance methods are invoked on the class instance, class methods are invoked on the class itself, and static methods are invoked on the class or instance of the class, but they do not have access to either. 

Contributed By: Abdulla

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio