Exploring Types of Methods in Python Classes

Published Aug. 29, 2023, 12:38 a.m.

In Python classes, three distinct types of methods play essential roles:

  1. Instance Methods:

Instance methods come into play when we utilize instance variables within their implementations. To declare an instance method, the self variable must be included.

def m1(self):
    # Method logic

By employing the self variable within the method, we gain access to the instance variables.

These methods can be called within the class using the self variable and from external sources using object references. They provide a way to interact with and manipulate object-specific data.

# Define a class named Student
class Student:
    # Constructor to initialize instance variables
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks
    
    # Instance method to display student information
    def display(self):
        print('Hi', self.name)
        print('Your Marks are:', self.marks)
    
    # Instance method to calculate and display grade
    def grade(self):
        if self.marks >= 60:
            print('You got First Grade')
        elif self.marks >= 50:
            print('You got Second Grade')
        elif self.marks >= 35:
            print('You got Third Grade')
        else:
            print('You are Failed')

# Get the number of students from the user
n = int(input('Enter number of students:'))

# Loop to input student information and display
for i in range(n):
    name = input('Enter Name:')
    marks = int(input('Enter Marks:'))
    # Create a Student object
    s = Student(name, marks)
    s.display()
    s.grade()
    print()

Output:

Enter number of students: 2
Enter Name: Alice
Enter Marks: 75
Hi Alice
Your Marks are: 75
You got First Grade

Enter Name: Bob
Enter Marks: 45
Hi Bob
Your Marks are: 45
You got Third Grade

Explanation:

  1. We define a class Student to encapsulate student information and behavior.
  2. The __init__ method (constructor) is used to initialize instance variables name and marks when creating a Student object.
  3. The display method is an instance method that displays the student's name and marks.
  4. The grade method is another instance method that calculates and displays the grade based on the student's marks.
  5. The loop (for i in range(n)) allows the user to input information for n students and display their details and grades.
  6. Inside the loop, we use the input function to get the student's name and marks from the user.
  7. We create a Student object s using the provided name and marks.
  8. We then call the display method and the grade method on the s object to show the student's information and grade.