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

Variables and Types

Variables and Types

Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.
Variable names can be a group of both letters and digits, but they have to begin with a letter or an underscore.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The rules to name an identifier are given below.
  • The first character of the variable must be an alphabet or underscore ( _ ).
  • All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore or digit (0-9).
  • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
  • Identifier name must not be similar to any keyword defined in the language.
  • Identifier names are case sensitive for example my name, and MyName is not the same.
  • Examples of valid identifiers : a123, _n, n_9, etc.
  • Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
Python does not bound us to declare variable before using in the application. It allows us to create variable at required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable that variable is declared automatically.
The equal (=) operator is used to assign value to a variable.
Eg: 
a=10
name = 'Manma'
salary = 800000.98
print(a)
print(name)
print(salary)
>>>Output
10
Manma
800000.98
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement which is also known as multiple assignment.
1.  Assigning single value to multiple variables
x=y=z=50  
print x
print y  
print z  
>>>Output
50
50
50
2. Assigning multiple values to multiple variables:
a,b,c=5,10,15
print a
print b
print c
>>>Output
5
10
15

Python Keywords, Literals, Operators & Comments

Keywords, Literals, Operators & Comments

Python Keywords
Python Keywords are special reserved words which convey a special meaning to the compiler/interpreter. Each keyword have a special meaning and a specific operation. These keywords can't be used as variable. Following is the List of Python Keywords.
True
False
None
and
as
asset
def
class
continue
break
else
finally
elif
del
except
global
for
if
from
import
raise
try
or
return
pass
nonlocal
in
not
is
lambda

Python Literals
Literals can be defined as a data that is given in a variable or constant.
Python support the following literals:
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String.
Eg:
"Aman" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a).Single line String- Strings that are terminated within a single line are known as Single line Strings.
Eg:
text1 = ‘hello’
b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.
There are two ways to create Multiline Strings:
1). Adding black slash at the end of each line.
Eg:
>>> text1='hello\ 
user' 
>>> text1 
'hellouser' 
2).Using triple quotation marks:-
Eg:
>>> str2='''''welcome
to
SSSIT''' 
>>> print str2 
welcome 
to 
SSSIT 

II.Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
Int(signed integers)        
Long(long integers)       
float(floating point)        
Complex(complex)

III. Boolean literals:
A Boolean literal can have any of the two values: True or False.

IV. Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for end of lists in Python.
Eg:
>>> val1=10 
>>> val2=None 
>>> val1 
10 
>>> val2 
>>> print val2 
None

V.Literal Collections.
Collections such as tuples, lists and Dictionary are used in Python.
List:
  • List contain items of different data types. Lists are mutable i.e., modifiable.
  • The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store different type of data in a List.
  • Value stored in a List can be retrieved using the slice operator([] and [:]).
  • The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
>>> list=['aman',678,20.4,'saurav'] 
>>> list1=[456,'rahul'] 
>>> list 
['aman', 678, 20.4, 'saurav'] 
>>> list[1:3] 
[678, 20.4] 
>>> list+list1 
['aman', 678, 20.4, 'saurav', 456, 'rahul'] 
>>> list1*2 
[456, 'rahul', 456, 'rahul']  

Python Operators

The operator can be defined as a symbol which is responsible for a particular operation between two operands. Operators are the pillars of a program on which the logic is built in a particular programming language. Python provides a variety of operators described as follows.

  • Arithmetic operators
  • Comparison operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

Arithmetic operators:
Arithmetic operators are used to perform arithmetic operations between two operands. It includes +(addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**).
Comparison Operators:
Comparison operators are used to comparing the value of the two operands and returns boolean true or false accordingly. It includes ==, !=, <=, >=, <>, >, <.
Python Assignment Operators:
The assignment operators are used to assign the value of the right expression to the left operand. It includes =, +=, -=, *=, %=, **=, //=.
Bitwise operators:
The bitwise operators perform bit by bit operation on the values of the two operands. It includes &(binary and), |(binary or), ^(binary xor), ~(negation), <<(left shift), >>(right shift).
Logical operators:
The logical operators are used primarily in the expression evaluation to make a decision. It includes not, and, or.
Membership operators:
Python membership operators are used to check the membership of value inside a data structure. If the value is present in the data structure, then the resulting value is true otherwise it returns false. It includes in and not in.
Identity operators:
is and is not are identity operators
Operator Precedence:
The precedence of the operators is important to find out since it enables us to know which operator should be evaluated first. The precedence table of the operators in python is given below.

Operator
Description
**
The exponent operator is given priority over all the others used in the expression.
~ + -
The negation, unary plus and minus.
* / % //
The multiplication, divide, modules, reminder, and floor division.
+ -
Binary plus and minus
>> <<
Left shift and right shift
&
Binary and.
^ |
Binary xor and or
<= < > >=
Comparison operators (less then, less then equal to, greater then, greater then equal to).
<> == !=
Equality operators.
= %= /= //= -= +=
*= **=
Assignment operators
is is not
Identity operators
in not in
Membership operators
not or and
Logical operators

Python Comments
Python supports two types of comments:
1) Single Line Comments
In case user wants to specify a single line comment, then comment must start with ?#?
Eg:
# This is single line comment.
2) Multiline comments
Multi lined comment can be given inside triple quotes.
Eg:
''''' This 
    Is 
    Multipline 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...