Featured

    Featured Posts

Python OOPS Tutorial 7:Types Of Method In Python



Types of Method In Python

 v There are three types of methods in Python:
1.     Instance Methods.
2.     Class Methods
3.     Static Methods
Instance Methods.

  §  Inside method implementation if we are using instance variables then such type of
           methods is called instance methods.

  §  If we want to access an instance variable or instance method, we must create an 
           object of that required class.

  §  This method can only be called if the class has been instantiated.

  §  Once an object of that class has been created the instance method can be called and 
     can access all the attributes of that class through the reserved word self.

  §  An instance method is capable of creating, getting and setting new instance 
           attributes and calling other instance, class and static methods.

class Calculator:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def add(self):
        return (self.a + self.b)
    def sub(self):
        return (self.a - self.b)
    def mul(self):
        return (self.a * self.b)
    def div(self):
        return (self.a /self.b)

c1 = Calculator(10, 20)
print("Addition= ",c1.add())
print("Substraction= ",c1.sub())
print("Multiplication= ",c1.mul())
print("Division= ",c1.div())

§  In the above program, a and b are instance variables and these get initialized when we create an object for the Calculator class. If we want to call add(),sub(),mul(),div() function which is an instance method, we must create an object for the class.

v Setter and Getter Methods:

 §  We can set and get the values of instance variables by using getter and setter methods. 
Accessor(Getters):

 § If you want to get values of the instance variables then we need to call them 
       getters (accessors) method.
syntax: 
 def  getVariable(self):
    return self.variable


Example: 
def  getName(self):
    return self.name

def  getAge(self):
    return self.age

Mutator(Setters): 
  §  If you want to modify the value of the instance variables. then we need to we call
          them mutators.

syntax: 
def  setVariable(self,variable):
    self.variable=variable 

Example:
def setName(self,name):
        self.name=name

Program:
class Person:
    def setName(self,name):
        self.name=name
    def getName(self):
        return self.name
    def setAge(self,age):
        self.age=age
    def getAge(self):
        return self.age

#create an Object
p1=Person()
p1.setName('john')
p1.setAge(101)
print("Name= ",p1.getName())
print("Age= ",p1.getAge())

Class Method

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

        Class Variable: A class variable is nothing but a variable that is defined outside the 
                                  constructor. A class variable is also called as a static variable.

  §  A class method is a method which is bound to the class and not the object of the  
             class.

  §  A class method is a class-level method.

  §  Class Method takes a class parameter that points to the class and not the object 
           instance. As we are working with ClassMethod we use the cls keyword.

  §    Class method can be called without having an instance of the class. 

How to define a class method

  §  To define a class method in python, we use @classmethod decorator in python to 
           create a class method.

@classmethod
    def method-name(cls):
        method-body

Program to demonstrate the class method:
class Car:
    wheels=4
    @classmethod
    def run(cls,name):
        print('{} runs with {} wheels...'.format(name,cls.wheels))

Car.run('Maruti')
Car.run('Ford')    

Program to track the number of objects created for a class:
class Demo:
    count=0
    def __init__(self):
        Demo.count=Demo.count+1

    @classmethod
    def noOfObjects(cls):
        print('The number of objects created for Demo class:',cls.count)  

#create an object
d1=Demo()
d2=Demo()
Demo.noOfObjects()
d3=Demo()
d4=Demo()
d5=Demo()
Demo.noOfObjects()

Output:
The number of objects created for Demo class: 2
The number of objects created for Demo class: 5

Static Methods
  §  In general, these methods are general utility methods.

  §  A static method is also a method which is bound to the class and not the object of 
          the class.

  §  Inside these methods we won't use any instance or class variables. They are utility 
           type methods that take some parameters and work upon those parameters.

  §  A static method does not receive an implicit first argument such as instance method       receive an implicit first argument as a self-variable and class method receive an  
            implicit first argument as a cls variable.

How to define a class method and a static method?

  §  to define a static method, we use @staticmethod decorator.

@staticmethod
    def method-name (arg1, agr2...):
        method-body

 §  You could use a static method when you have a class but you do not need an specific  
       instance in order to access that method. For example if you have a class called Math 
       and you have a method called factorial (calculates the factorial of a number).


class Math:
    @staticmethod
    def factorial(number):
        if number == 0:
            return 1
        else:
            return number * Math.factorial(number - 1)

factorial = Math.factorial(5)
print(factorial)

Class method vs Static Method

  §  A class method implicitly takes cls as first parameter while a static method needs 
          no specific parameters.

  § If we define any method inside class by decorating @classmethod decorator is 
          known as class method while defining a method inside by decorating 
          @staticmethod decorator is known as static method.

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

  §  Inside method implementation if we are not using any instance or class variables 
          then such type of methods we should declare as static method for utility purpose.







author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews