Methods in Python

Methods are another kind of Functions associated with the classes.

Inside the Python class, three types of methods are allowed

Instance Methods in python

Inside method implementation, if we are using instance variables, then such kind of plans are called instance methods.

Inside the instance method declaration, we have to pass the self variable.

Example: def m1(self):

The First Argument to the instance method is always self, which is a reference variable to that object.

By using the self variable inside a method, we can able to access instance variables. Within the class, we can call the instance method by using the self variable, and from outside of the class, we can call by using object reference.

The following example demonstrates the Instance Method

class Student:
    def __init__(self,name,marks):
        self.name=name
        self.marks=marks
        
    def display(self):
        print("Hello", self.name)
        print("your marks are:", self.marks)
        
    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")
            
n=int(input("Enter Number of students:"))
for i in range(n):
    name=input("Enter Student Name:")   
    marks=int(input("Enter Student Marks:"))
    s=Student(name,marks)
    s.display()
    s.grade()
    print()

The output is:

instance-method-application

Setter and Getter Methods

Setter and Getter's methods are two special kinds of variables used to set and get the values of instance variables.

The IDE(Integrated Development Environment) is responsible for generating setter and getter methods.

Setter:

The setter method is also known as Mutator Method; the Setter method is responsible for setting or changing the values of the instance variable.

The syntax for the setter method is:

def set instance variable(self, instance variable)
      self.instance varaible=instance varaible

Example:

def setmarks(self,marks)
      self.marks=marks

Getter:

The getter method is also known as an accessor method; Getter is responsible for getting the values of an instance variable.

The Syntax for the Getter method is:

def getinstance variable(self):
      return self.instance variable

Example:

def getmarks(self)
      return self.marks

The Following example Demonstrates the getter and setter methods:

class Student:
    def setName(self,name):
        self.name=name
    def getName(self):
        return self.name
    def setMarks(self,marks):
        self.marks=marks
    def getMarks(self):
        return self.marks
n=int(input("Enter the Number of Students:"))
students=[]
for i in range(n):
    s=Student()
    name=input("Enter the Student Name:")
    marks=int(input("Enter the Student Marks:"))
    s.setName(name)
    s.setMarks(marks)
    students.append(s)
for s in students:
    print("Hi",s.getName())
    print("Your Marks are:",s.getMarks())
    print() 

The output is:

getter-and-setter-methods

Python Operators

Class Methods in python

Inside method implementation, if we are using only class variables (static variables), then such type of methods, we should declare a class method.

We can declare the class method explicitly by using @classmethod decorator. For the class method, we should provide a cls variable at the time of the declaration. We can call the classmethod by using the classname or object reference variable.

The First argument to the class method is always cls, and it is the reference variable to a current class object; by using cls, we can access the class-level data.

For every class, one special object will be created by python virtual machine to maintain the class level information, which is nothing but a class level object, cls is the reference variable pointing to that object.

class Test:
    @classmethod
    def m1(cls):
        print(id(cls))
print(id(Test))
Test.m1()

The output is:

class-method

Example:

class Bird:
    wings=2
    @classmethod
    def fly(cls,name):
        print("{} flying with {} wings".format(name,cls.wings))

Bird.fly("parrot")
Bird.fly("Eagle")

The output is:

bird-example

The following example demonstrates the number of objects created for a class

class Test:
    count=0
    def __init__(self):
        Test.count=Test.count+1
        
    @classmethod
    def getNoOfObjects(cls):
        print("The Number of Objects Created:",cls.count)
            
Test.getNoOfObjects()    

The output is: When we have not created any objects

when-zero-objects-created

When we created four objects

class Test:
    count=0
    def __init__(self):
        Test.count=Test.count+1
        
    @classmethod
    def getNoOfObjects(cls):
        print("The Number of Objects Created:",cls.count)
            
Test.getNoOfObjects()    
t1=Test()
t2=Test()
t3=Test()
t4=Test()
Test.getNoOfObjects() 

The output is:

when-created-four-objects

Difference Between Instance Method and Class Method

Instance Method Class Method
Inside the method body, if we are using at least one instance variable then compulsory, we should declare that method as an instance method Inside the method body if we are using a static variable and not using instance variable, then we should declare that method as a class method
Inside the instance method, we can access both instance and static variables Inside the static method, we can access the only static variable and not instance variable
To declare an instance method, we are not required to use any decorator To declare a static method, we should be required to use any @classmethod decorator
The First argument to the instance method is self, which is a reference to the current object and by using self, we can access the instance variable inside the method The First argument to classmethod is cls, which is a reference to the current class object and by using cls, we access static variables
We can call the instance method by using the object reference We can call the static method either by using the object reference or by using the class name but recommended touse class name

Python Modules

Static Methods in python

Inside a method, if we are not using any static variable and instance variable, then such type of methods are general utility methods, and these methods we declare as static methods.

For a static method, we won't provide any self or cls at the time of declaration.

We can declare a static method explicitly by using @staticmethod decorator

We can access the static method either by using the object reference or by using the class name. But not recommended to use a class name.

@staticmethod
def getsum(a,b):
      sum=a+b
      return sum

The following example demonstrates the static method

class FavMath:
    @staticmethod
    def add(a,b):
        print("The Sum is:",a+b)
        
    @staticmethod
    def product(a,b):
        print("The Product is:",a*b)
        
    @staticmethod
    def average(a,b):
        print("The Average is:",(a+b)/2)
        
FavMath.add(20,10)
FavMath.product(20,10)
FavMath.average(20,10)   

The output is:

static-method-application

Difference between Instance method, class method, and static methods

InstanceMethod Class Method Static Method
We should call the instance method by using an object reference only We can declare a class method explicitly by using the @classmethod decorator, and we can call these methods either by using object reference or class name We can declare a static method explicitly by using the @staticmethod decorator, and we can call these methods either by using object reference or class name
If we are using only the instance variable, then it is an instance method If we are using only a Static variable, then it is a classmethod If we are using the Instance variable and static variable, then it is a Static method
If we are using Instance variable and a local variable, then it is an instance method If we are using a Static variable and Local variable, then it is a static method If we are using only a local variable, then it is a static method

Without any decorator, the method can be either an instance method or static method,

If we are calling by using object reference, then it is treated as an Instance method

For Classnmethod, @classmethod decorator is mandatory

For Static method, @staticmethod decorator is optional

If we are calling by using class name, then it is treated as a static method

The following example demonstrates if we are not passing any arguments inside the instance method, then Python will throw an error

class Test:
         def method():
               print("SomeMethod")
t=Test()
t.method()

The output is:

instance -method-without-passing-any-argument

In instance, method by default, python provides a self argument, but in the above example, we have not passed any arguments. That's why it is showing an error.

In the below example we are passing a self argument as x, and while calling the method, we are providing value as 10 to the second method, so python throws an error because for the self argument python is responsible to provide the value

class Test:
         def method(x):
               print("SomeMethod")
t=Test()
t.method()
t.method(10)

The output is:

examples-of-instance-static-methods

The following example contains the static method, and hence, the method does not contain any argument, and while calling the method, we are not passing any value.

class Test:
         def method():
               print("SomeMethod")
Test.method()

The output is:

static-method-without-any-arguments

The following example contains a static method because we are not using any decorator, and if we call any method without passing any value, then the python will throw an error as it is expecting one positional argument.

class Test:
         def method(x):
               print("SomeMethod")
Test.method()

The output is:

expecting-one-positional-argument

Accessing the members of one class inside the other class

The following example demonstrates accessing the members of one class inside the other class

class Employee:
         def __init__(self,eno,ename,esal):
             self.eno=eno
             self.ename=ename
             self.esal=esal
         def display(self):
               print("Employee Number:",self.eno)
               print("Employee Name:",self.ename)
               print("Employee Salary:",self.esal)
               
class Manager:
    def updateEmpSal(emp):
        emp.esal=emp.esal+10000
        emp.display() ## accessing the members of one class inside the another class
       
emp=Employee(101,"Nitya",45000)
Manager.updateEmpSal(emp)

The output is:

employee-sal-details

Python Input and Output Statements

Inner Classes in python

Defining a class inside another class are called inner classes

Without existing one type of object, if they're no chance of existing a different kind of object, then we should go for inner classes.

The Advantages of Inner Classes

  • Improves the Modularity of the application
  • Enhances the Security of the application

Example: Without existing university object, there is no chance of existing department object; the department should be a part of the university and cannot exist alone; hence, we should declare depart class inside university class.

class University:
     class Department:
          pass        

The following example demonstrates the outer and inner object creation

class Outer:     ##declaring outer class
    def __init__(self):
        print("Outer class object creation...")
    class Inner:                                    ##declaring inner class
        def __init__(self):
            print("Inner class object craetion...")
        def method1(self):
            print("Inner class Method...")
 
o=Outer()   ##Creating outer object
i=o.Inner()   ##by using outer object, craeting inner object
i.method1()        ##by using inner object calling method1   

The output is:

creating-inner-and-outer-class

Nesting of inner classes

Example1:

class Outer:
    def __init__(self):
        print("Outer class object creation...")
    class Inner:
        def __init__(self):
            print("Inner class object craetion...")
        class InnerInner:
            def __init__(self):
                print("InnerInner class object creation...")
            def method1(self):
                print("Inner class Method...")
 
o=Outer()
i=o.Inner()
ii=i.InnerInner()
ii.method1()     

The output is:

nesting-of-inner-class

The Nested inner class may also contain a static method also

class Outer:
    def __init__(self):
        print("Outer class object creation...")
    class Inner:
        def __init__(self):
            print("Inner class object craetion...")
        class InnerInner:
            def __init__(self):
                print("InnerInner class object creation...")
            @staticmethod    
            def method1():
                print(" Nested Inner class Method...")
 
Outer().Inner().InnerInner().method1()   ## calling static method by using object reference

The output is:

nested-inner-class-static-method

Without creating an internal class object, we can call the static method by using the class name

class Outer:
    def __init__(self):
        print("Outer class object creation...")
    class Inner:
        def __init__(self):
            print("Inner class object craetion...")
        class InnerInner:
            def __init__(self):
                print("InnerInner class object creation...")
            @staticmethod    
            def method1():
                print("Nested Inner class Method...")
 
Outer().Inner().InnerInner.method1() 

The output is:

calling-static-method-by-using-class-name

Example2:

class Human:
    class Head:
        def talk(self):
            print("Talking..")
        class Brain:
            def think(self):
                print("Thinking...")
                
human=Human()   ##Creating human object
head=human.Head()  ##by using human object, creating head object
head.talk()  ##by using head object, calling talk method
brain=head.Brain() ## by using head object, creating brain object
brain.think()    ##by using batin object calling think method

The output is:

creating-inner-class-head-and-human-objects

Example3:

class Human:
    def __init__(self,name):
        print("Human Object Creation...")
        self.name=name
        self.head=self.Head()
        
    def info(self):
        print("Hello My self:",self.name)
        print("I am Full busy with,")
        self.head.talk()
        self.head.brain.think()
        
    class Head:
        def __init__(self):
            print("Head Object Creation..")
            self.brain=self.Brain()
        def talk(self):
            print("Talking......")
            
        class Brain:
            def __init__(self):
                print("Brain Object Creation...")
            def think(self):
                print("Thinking...")
                
human=Human("Dhan")                
human.info()

The output is:

Automatic-calling-head-human-object

Example 4:

class person:
    def __init__(self):
        print("Person Object Creation..")
        self.dob=self.Dob()
    class Dob:
        def __init__(self):
            print("DOB Object Creation..")
#whenever we create a person object then automatically dob object got created            
p=person()          

The output is:

person-object-and-dob-object-creation

Example 5:

class Person:
    
    def __init__(self,name,dd,mm,yyyy):
        print("Person Object Created..")
        self.name=name
        self.dob=self.Dob(dd,mm,yyyy)
        
    def info(self):
        print("Name:",self.name)
        self.dob.display()
        
    class Dob:
         
         def __init__(self,dd,mm,yyyy):
             print("DOB Object Creation..")
             self.dd=dd
             self.mm=mm
             self.yyyy=yyyy
             
         def display(self):
             print("DOB={}/{}/{}".format(self.dd,self.mm,self.yyyy))
     
p=Person("Anju",20,1,1992) 
p.info()       

The output is:

creating-dob-and-person-creation

Python Logging

Nested Methods in python

We can declare a method inside a method, such type of methods are called as Nested Methods.

Inside a method, if any functionality is repeatedly required, that functionality we can define as a separate, and we can call that method any number of times based on our requirement.

The Advantages of Nested Methods are :

  • Code Reusability will be improved
  • The modularity of the application will be improved

The following example demonstrates the Nested Methods

class Test:
    def method1(self):
        def calc(a,b):
            print("The Sum:",a+b)
            print("The Product is:",a*b)
            print("The Difference is:",a-b)
            print("The Avarage is:",(a+b)/2)
            print()
        calc(10,20)
        calc(50,20)
        calc(200,50)
t=Test()
t.method1()        

The output is:

nested-method-program









Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions