Thursday, 26 December 2019

Python OOPs Concepts

Python is also an object-oriented language since its beginning. It allows us to develop applications using an Object Oriented approach. In Python, we can easily create and use classes and objects.
Major principles of object-oriented programming system are given below.
  • Object
  • Class
  • Method
  • Inheritance
  • Polymorphism
  • Data Abstraction
  • Encapsulation
Object : The object is an entity that has state and behavior. Everything in Python is an object, and almost everything has attributes and methods.
Class : The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods.
Example:
class Employee:
    incremnt = 1.5
    no_of_employee=0
    def __init__(self, fname, lname, salary):
        self.fname = fname
        self.lname = lname
        self.salary = salary
        Employee.no_of_employee += 1
    def increment(self):
        print(self.incremnt)
        print(Employee.incremnt)
        self.salary = int(int(self.salary) * Employee.incremnt)

Method : The method is a function that is associated with an object.
Example:
def increment(self):
    self.salary = int(int(self.salary) * self.incremnt)
    print(self.salary)

Inheritance : By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class.
It provides re-usability of the code.
Example:
class Employee:
    incremnt = 1.5
    no_of_employee=0
    def __init__(self, fname, lname, salary):
        self.fname = fname
        self.lname = lname
        self.salary = salary
        #self.incremnt = 1.2
        Employee.no_of_employee += 1
    def increment(self):
        print(self.incremnt)
        print(Employee.incremnt)
        self.salary = int(int(self.salary) * Employee.incremnt)
    @classmethod
    def change_increment(cls,amount):
        cls.incremnt = amount
class Programmer(Employee):
    def __init__(self,fname,lname,salary,proglang, exp):
        super().__init__(fname,lname,salary)
        self.proglang = proglang
        self.exp = exp
    def increment(self):
        self.salary = int(int(self.salary)*self.incremnt)
umesh = Programmer('umesh','verma','45880','Python','8 years')
print(umesh.salary)
umesh.increment()
print(umesh.salary)

Polymorphism : Polymorphism contains two words "poly" and "morphs". Poly means many and Morphs means form, shape. By polymorphism, we understand that one task can be performed in different ways.
Example:
class India(): 
    def capital(self): 
        print("New Delhi is the capital of India.") 
    def language(self): 
        print("Hindi the primary language of India.") 
    def type(self): 
        print("India is a developing country.") 
class USA(): 
    def capital(self): 
        print("Washington, D.C. is the capital of USA.") 
    def language(self): 
        print("English is the primary language of USA.") 
    def type(self): 
        print("USA is a developed country.") 
obj_ind = India() 
obj_usa = USA() 
for country in (obj_ind, obj_usa): 
    country.capital() 
    country.language() 
    country.type() 
Output:
New Delhi is the capital of India.
Hindi the primary language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Encapsulation : Encapsulation is also an important aspect of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.
Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.
Public members are those members of the class which can be accessed outside the class environment.
Protected members are those members of the class which cannot be accessed outside the class but can be accessed from within the class and it’s subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore "_".
Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private instance variables that cannot be accessed except inside a class. However, to define a private member prefix the member name with double underscore "__".
Example :
class Computer:
    def __init__(self):
        self.__maxprice = 900
    def sell(self):
        print("Selling Price: {}".format(self.__maxprice))
    def setMaxPrice(self, price):
        self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Output:
Selling Price: 900
Selling Price: 900
Selling Price: 1000

Data Abstraction : In python by default, it is not able to provide abstract classes, but python comes up with a module which provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by marking methods of the base class as abstract and then registering concrete classes as implementations of the abstract base. A method becomes an abstract by decorated it with a keyword @abstractmethod.
For Example:
# Python program showing 
# abstract base class work 
from abc import ABC, abstractmethod 
class Polygon(ABC): 
    # abstract method 
    def noofsides(self): 
        pass
class Triangle(Polygon): 
    # overriding abstract method 
    def noofsides(self): 
        print("I have 3 sides") 
class Pentagon(Polygon): 
    # overriding abstract method 
    def noofsides(self): 
        print("I have 5 sides") 
class Hexagon(Polygon): 
    # overriding abstract method 
    def noofsides(self): 
        print("I have 6 sides") 
class Quadrilateral(Polygon): 
    # overriding abstract method 
    def noofsides(self): 
        print("I have 4 sides") 
# Driver code 
R = Triangle() 
R.noofsides() 
K = Quadrilateral() 
K.noofsides() 
R = Pentagon() 
R.noofsides() 
K = Hexagon() 
K.noofsides() 
Output:
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides

No comments:

Post a Comment

Python Datatype Interview Questions

Q)  What is Python? Python is a high-level, interpreted, interactive, and object-oriented scripting language. Python is designed to be...