Methods in Python with Examples

FREE Online Courses: Elevate Your Skills, Zero Cost Attached - Enroll Now!

In Python, a Function is a block of code that accomplishes a certain task. A function inside a class and associated with an object or class is called a Method. 

Similar to functions, methods also have a name, parameters, and a return statement. Classes can bundle data and functionality together. We use methods to provide the functionality to a class. 

Creating a method in python

We can define a method by using the def keyword and the basic syntax of the method is following:

Syntax of creating Method in Python

class ClassName:
   def method_name(*args):
       # Statements..

Using the above syntax, we can create a method but first let’s create a class for our method.

class Student:
   pass

student1 = Student()
print(f"Object Created: {student1}")

Output

Object Created: <__main__.Student object at 0x10b4fc310>

In the above code, we have created an empty class and an object to the class. Until now, the object doesn’t have any behavior that is functional. To give functionality to our empty class, we need to define a method.

class Student:

   def study(self):
       return "Student is studying..."

student1 = Student()
print(f"Object Created: {student1}")s

Output

Object Created: <__main__.Student object at 0x10b4fc310>

In the above example, we created a method study() in the class StudentIgnore the self parameter, for now, we will learn about it in the coming sections. 

With the help of the method, the object of our class has a behavior but how do we access the method?

Accessing Methods in python

We can access a method just like an attribute by using the dot operator and either the object name or the class name depending on the type of the method.

Syntax

object_name.method_name(*args)

Or

ClassName.method_name(*args)

For Example

print(student1.study())

Output

Student is studying…

In the above example, we called the method study() by using the dot operator. 

Types of methods in Python

In Python, we can create different types of methods. These are

Instance Methods Static Methods
Class Methods Magic Methods

Instance methods in Python

Instance methods can only be accessed by object name.

For example

class Student:

    no_of_students = 10

    def __init__(self, name, age):
       self.name = name
       self.age = age

    def birthday(self):
       self.age += 1
       return f"{self.name} has now turned {self.age}\n" \
              f"{self.no_of_students - 1} students of his" \
              f" class have sent Birthday gifts."

student1 = Student("Chan", 13)

print(student1.birthday())

Output

Chan has now turned 14
9 students of his class have sent Birthday wishes.

In the above code example, we created two instance methods, __init__() method and birthday() method. We have called the birthday() method using the dot operator and the object name.

__init__() is also called a magic method, we will learn about it in the next section. 

We can notice that both these methods have a common parameter self in their class definition. All instance methods take the first parameter self and the value of self is automatically given by Python.

The parameter self, similar to a pointer in C language, references to the current object of the class. Using self, instance methods can access and alter the state/attributes of an object.  

In the above code example, the method birthday accessed the object’s name and age attributes and altered the age attribute by incrementing its value. 

Instance Methods can also access and modify the state/attributes of a class by using the self.__class__ attribute. 

In the above code example, the method birthday accessed the class’s attribute no_of_students

Instance methods are bound to the object and the attributes in the Instance methods can not be shared among objects.

Self Parameter in Python

All instance methods in a class have a parameter called self in their method definition. The address of the object is passed as an argument to this parameter. Unlike other parameters, the value of the argument is provided directly by Python.

For Example

class Student:

   def study(self, hours):
       self.hours = hours
       return f"Studying {self.hours} hours ..."

student1 = Student()

print(student1.study(10))

Output

Studying 10 hours …

In the above code, whenever we call the method, Python automatically converts the last line into the below code.

For Example

print(Student.study(student1, 10))

Output

Studying 10 hours …

This is why we do not need to pass any value to the parameter self.

We can use any other name instead of self as long as it is the first parameter in the method definition.

For Example

class Student:

   def study(any_name, hours):
       any_name.hours = hours
       return f"Studying {any_name.hours} hours ..."

student1 = Student()
print(student1.study(10))

Output

Studying 10 hours …

In the above code example, we named the first parameter any_name instead of self and it still worked perfectly.

When to use Instance Methods in Python

When different objects need different values and functionality. We use instance methods to provide unique values and functionality to objects.

For Example

class Vehicle:

   def __init__(self, make, model):
       self.make = make
       self.model = model

car1 = Vehicle("Audi", "EQ")
car2 = Vehicle("BMW", "M2")

print("Car 1 details")
print(car1.make, car1.model)
print("Car 2 details")
print(car2.make, car2.model)

Output

Car 1 details
Audi EQ
Car 2 details
BMW M2

In the above code example, both objects have unique values for make and model attributes.

Class methods in Python 

To create a class method, we need to use a decorator @classmethod

Class methods can be accessed either by the class name or the object name.

For Example

class Student:

   no_of_students = 10

   def __init__(self, name, age):
       self.name = name
       self.age = age

   def birthday(self):
       self.age += 1
       return f"{self.name} has now turned {self.age}\n" \
              f"{self.no_of_students - 1} students of his" \
              f" class have sent Birthday gifts"

   @classmethod
   def add_a_student(cls):
       cls.no_of_students += 1

   @classmethod
   def total_students(cls):
       return f"Class has {cls.no_of_students} students"

student1 = Student("Chan", 13)

student1.add_a_student()
print(Student.total_students())

Output

Class has 11 students

In the above code example, we added two class methods to the class Student. We accessed the methods add_a_student() using the object name and total_students() using the class name.  

Our two class methods have a common parameter cls. All class methods take the first parameter cls. 

The parameter cls references to the Class. Since cls parameter references to the class, it can access and modify only the class state. 

In our class Student, whenever the class method total_students() is called, it accesses the class attributes and returns a string. The method add_a_student() modifies the class attribute no_of_students by increasing it

Class methods are bound to the class and the attributes inside the class method are shared among all objects of the class. 

Cls Parameter in Python

For Example

class Website:
   name = "PythonGeeks"

   @classmethod
   def details(cls):
       return f"Website is {cls.name}"

print(Website.details())

Output

Website is PythonGeeks

Similar to the self parameter, all class methods in a class have a parameter called cls in their method definition. The address of the class is passed as an argument to this parameter. Unlike other parameters, the value of the argument is provided directly by Python. 

We can use any other name instead of cls as long as it is the first parameter in the method definition.

For Example

class Website:
   name = "PythonGeeks"

   @classmethod
   def details(any_name):
       return f"Website is {any_name.name}"

print(Website.details())

Output

Website is PythonGeeks

When to use Class Methods in Python?

We use class methods, when all objects have the same values for certain attributes or when dealing with attributes that represent the entire class.

We also use class methods to create objects like a constructor. These types of methods are called Factory methods.

For Example

import math

class Square:
   def __init__(self, side):
       self.side = side

   @classmethod
   def side_from_area(cls, area):
       side = math.sqrt(area)
       return cls(side)

s1 = Square.side_from_area(16)
print(s1.side)

Output

4.0

In the above code example, we created a class method that returns an object. Generally, we need to know the side length of a square to create an object. But the new class method side_from_area() creates an object using the value of area rather than side length.

Static methods in Python

To create a static method, we need to use the decorator @staticmethodSimilar to class methods, static methods can also be accessed either by the class name or the object name.

For Example

class Student:

   no_of_students = 10

   def __init__(self, name, age):
       self.name = name
       self.age = age
       self.dob = None

   def birthday(self):
       self.age += 1
       return f"{self.name} has now turned {self.age}\n" \
          f"{self.no_of_students - 1} students of his" \
              f" class have sent Birthday gifts"

   @classmethod
   def add_a_student(cls):
       cls.no_of_students += 1

   @classmethod
   def total_students(cls):
       return f"Class has {cls.no_of_students} students"

   @staticmethod
   def dob_format(raw_date):
       return raw_date.replace("-", "/")

   def get_dob(self, date):
       formatted_date = self.dob_format(date)
       self.dob = formatted_date

student1 = Student("Chan", 13)

student1.get_dob("11/12/2002")
print(student1.dob)

print(Student.dob_format("14-02-2001"))

Output

11/12/2002
14/02/2001

In the above code example, we added a static method dob_format() and an instance method get_dob() which calls the static method using the object address. We accessed the method dob_format() using the class name as well.  

Unlike Instance and Class methods, Static methods don’t take any implicit first arguments because it does not access or modify both the instance and class state. 

Static methods are mostly utility functions. They can work even outside the class but it makes more sense to keep them in the class.

In the above code example, the static method dob_format() can be placed outside the class like a normal function but it makes more sense to define it inside a class because it helps the class in formatting the object’s date. Static methods are bound to the class just like class methods.

When to use Static Methods in Python?

Static methods are used to create utility functions. 

For Example

class Square:
   def __init__(self, side):
       self.side = side

   @staticmethod
   def find_area(side):
       return side * side

print(Square.find_area(4))

Output

16

In the above code example, we do not need to create an object when we need to find an area of the square.  This makes finding the area of a square simpler and faster. 

Instance Methods vs Class Methods vs Static Methods

Instance Methods Class Methods Static Methods
Have a parameter self Have a parameter cls No such parameters
Bound to Object Bound to Class Its also Bound to class
Called by object name Called by both object name and class name It’s called by both object name and class name
No decorator is needed @classmethod decorator is needed @staticmethod decorator is needed
Can modify/alter both the object’s and class’s state Can modify/alter only the class’s state It can not modify/alter both the object’s and class’s state

Magic methods in Python

Magic methods are methods that have two prefix underscores and two suffix underscores. They are also called Dunder methods. In this context, Dunder means Double Under (underscores). We never directly invoke these methods.

Magic methods are invoked indirectly by Python in the background. All these magic methods are defined in the Python built-in classes. We can override them whenever we need them.  

List of Magic Methods and Their Uses

Magic Method Use
__new__ Creates an instance of the class
__init__ Instantiates the class
__del__ Deletes an object
__delete__ Deletes an attribute of the parent class
__getattr__ Returns the value of a specific attribute
__hasattr__ Checks whether an attribute exists or not
__setattr__ Modifies an existing attribute or creates a new attribute 
__delattr__ Deletes an attribute
__dict__ Returns a dictionary of attributes and values
__dir__ Returns a list of valid attributes
__format__ Represent an object in various string forms
__hash__ Converts object to an integer
__str__ A string representation of an object
__repr__ An official string representation of an object
__sizeof__ Size of object in memory, in bytes.
__bytes__ Get an immutable bytes object initialized with given data and size
__bytearray__ Returns an array of given bytes
__weakref__ Returns a list of weak references to the object
__contains__ Checks whether a character exists or not in a string
__len__ Returns the length of a string
__add__ Returns the addition of two numbers
__sub__ Returns the difference of two numbers
__mul__ Returns the product of two numbers
__truediv__ Returns the division of two numbers
__eq__ Checks whether two numbers are equal or not. Returns True if equal. 
__ne__ Checks whether two numbers are equal or not. Returns True if not equal.
__lt__ Checks whether a number is less than the other number
__ge__ Checks whether a number is greater than the other number
__le__ Checks whether a number is less than or equal to the other number
__ge__ Checks whether a number is greater than or equal to the other number
__int__ Converts a number or string to integer
__float__ Converts a number or string to float
__floordiv__ Returns an integer type quotient of division
__round__ Rounds to the nearest integer value
__ceil__ Returns the smallest integer greater than the given value
__floor__ Returns the greatest integer lesser than the given value
__trunc__ Removes the decimal part of the value
__abs__ Returns the absolute value of a number
__pow__ Returns the exponential of the given values
__mod__ Returns the modulus of the given values
__getitem__ Returns the value of the given key
__setitem__ Modify an existing value or set a new value to the given key
__delitem__ Deletes a value and key of the given key
__iter__ Returns an iterator

Let’s see a few examples to understand the working of Magic Methods.

Examples of Magic Methods in Python

1. __new__()

Whenever we define an object, the __new__()  method is called to create that object. We can see this by overriding the method to print a string when called.

For Example

class Fruit:

   def __new__(cls, *args, **kwargs):
       print("Object Created")
      
fruit1 = Fruit()

Output

Object Created

Example

2. __init__()

After creating the object, __init__() is called to instantiate the object. It is similar to a constructor in Java and C++.  The arguments for this method should be passed while creating the object. 

Example

class Fruit:

   def __init__(self, name):
       self.name = name
       print(f"{self.name} is a fruit")

fruit1 = Fruit("orange")

Output

orange is a fruit

3. __sub__()

It is present in the class int. Whenever we use the operator , Python internally calls the __sub__() method.

class Fruit:

   def __init__(self, fruits):
      self.fruits = fruits

   def __sub__(self, other):
       return f"{self.fruits} fruits - {other.fruits}" \
              f" fruits = {self.fruits - other.fruits} fruits"


fruit1 = Fruit(10)
fruit2 = Fruit(3)

print(fruit1 - fruit2)

Output

10 fruits – 3 fruits = 7 fruits

In the above code example, we redefined the __sub__ method. This is called operator overloading.

Method Overriding in Python

Creating a method with the same name and parameters as the method in the parent class is called Method overriding.

When we inherit a class, the child class inherits all the methods of the parent class.

Example of Method Overridin

class ParentClass:

   def get_info(self):
       print("Parent class")

class ChildClass(ParentClass):
   pass

child = ChildClass()
child.get_info()

Output

Parent class

In the above code example, although ChildClass is empty, it still invokes the get_info method because ChildClass inherited the get_info method from the parent class.

For Example

class ParentClass: 

   def get_info(self): # old method
       print("Parent class")

class ChildClass(ParentClass): 

   def get_info(self): # new method
       print("Child class")

child = ChildClass()
child.get_info()

Output

Child class

In the above code example, when we define a method in the ChildClass with the same name as a method in the parent class, the new method overrides the old method in the ParentClass and invokes the new method in the ChildClass when called rather than the old method in the ParentClass.

In the above code example, Python invokes the new method in the ChildClass because the new method overrides the old method in the ParentClass.

This comes in handy when we want to change the behavior of a method in the child class that is already defined in the parent class.

Method Overloading in Python

Creating a new method with the same name as an already existing method but with different parameters is called method overloading.

Unlike other Object-Oriented programming languages, Python does not directly support method overloading. 

When we define a new method with the same name as an old method but with different parameters, Python replaces the old method with the new method instead of overloading.

class Car:

   def drive(self): # Old method
       print("Driving")

   def drive(self, speed): # new method
       self.speed = speed
       print(f"Driving at {self.speed} km/h")

car1 = Car()
car1.drive()

Output

TypeError: drive() missing 1 required positional argument: ‘speed’

When we run the above code example, Python raises a TypeError instead of calling the old method drive(). This is because Python replaced the old method drive() with the new method drive(speed) and the old method drive() doesn’t exist anymore.

Operator Overloading in Python

Changing the behaviour of an operator by redefining the method an operator invokes is called Operator Overloading.

Whenever we use an operator, a method corresponding to that operator is invoked. For example, when  we use + operator,  __add__ magic method gets invoked and when we use * operator, __mul__ method gets invoked. 

We can redefine such methods in our class to change the behavior of operators. For example, we can make Python return a string when we use + operator instead of adding the arguments. 

For Example

class Multiply:

   def __init__(self, value):
       self.value = value

   def __mul__(self, other):
       result = self.value * other.value
       return f"Multiplying {self.value} and {other.value},"\ 
              f" we get {result}"

m1 = Multiply(5)
m2 = Multiply(2)

print(m1*m2)

Output

Multiplying 5 and 2, we get 10

In the above code example, we redefined the __mul__ method in our class. When we used * operator, Python invoked __mul__ method which returned a string.

Python Interview Questions on Methods in Python

Q1. Complete the following code by creating two methods. One method should update the money attribute and another method should return the money attribute. 

Code

class Wallet:

   def __init__(self):
       self.money = None  

   # Your Code Here...

my_wallet = Wallet()
my_wallet.set_money(50_000)
print(my_wallet.get_money())

Ans 1.

class Wallet:

   def __init__(self):
       self.money = None

   # Your Code Here...

   def set_money(self, rupees):
       self.money = rupees

   def get_money(self):
       return self.money

my_wallet = Wallet()

my_wallet.set_money(50_000)
print(my_wallet.get_money())

Output

50000

Q2. Create a class named Circle and initialise with radius. Create methods to find circumference and area.

Hint

a.  Area formula – r2

b. Circumference formula – 2r

c. Value of pie is found in the math module.

Ans 2. Code is as follows:

from math import pi
class Circle:

   def __init__(self, radius):
       self.radius = radius

   def area(self):
       return round(pi * pow(self.radius, 2), 2)

   def circumference(self):
       return round(2 * pi * self.radius, 2)

circle1 = Circle(25)

print("Radius = ", circle1.radius)
print("Area = ", circle1.area())
print("Circumference = ", circle1.circumference())

Q3. For the class Student, create a method as follows:

a. The method should have neither self nor cls parameters.

b. The method should have one parameter which takes the marks of the student.

c. The method can be called by using both the class name or object name.

d. Grade A for more than 90, grade B for more than 70-90, grade C for 50-70, grade D for 30 – 50 and grade F for less than 30 marks.

Ans 3. Code is as follows:

class Student:

   @staticmethod
   def grade(marks):

       if marks > 90:
           return "A"
       elif marks > 70:
           return "B"
       elif marks > 50:
           return "C"
       elif marks > 30:
           return "D"
       else:
           return "F"

print(Student.grade(20))
s1 = Student()
print(s1.grade(100))

Output

F
A

Q4. A company has 134 employees each getting a paycheck worth 25,000 INR per month. Create two methods in the class Employee. One method should return the total number of employees and each employee’s salary and using that data another method has to calculate how much money is being spent for salaries per month. Both methods should be called using the class name.

Ans 4. 

class Employee:

   @classmethod
   def employee_details(cls):
       cls.employees = 134
       cls.salary_month = 25_000
       return cls.employees, cls.salary_month

   @classmethod
   def total_salaries_month(cls):
       total_employees, emp_salary = cls.employee_details()
       total = total_employees * emp_salary
       return total

print(Employee.total_salaries_month())

Output

3350000

Q5. Complete the code by overriding a magic method to get the sample output. 

class Addition:
   # Your Code Here...

num1 = Addition(10)
num2 = Addition(20)
print(num1 + num2)

Output

10 + 20 = 30

Ans 5. Complete code is as follows:

class Addition:
   # Your Code Here...

   def __init__(self, value):
       self.value = value

   def __add__(self, other):
       return f"{self.value} + {other.value} =" \
              f" {self.value + other.value}"

num1 = Addition(10)
num2 = Addition(20)
print(num1 + num2)

Output

10 + 20 = 30

Quiz on Methods in Python

Conclusion

In this article, we learned about the Python methods, types of methods and how to use them. If you have any queries or thoughts, please feel free to share them with us in the comment section.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *