Python Oops Concept
Python Oops Concept
Public:
The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the
package and outside the package.
Private:
The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Protected:
The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the
child class, it cannot be accessed from outside the package.
By default, all the variables and member functions of a class are public in
a python program.
class Employee:
# constructor
def __init__(self, name, sal):
self.name = name
self.sal = sal
All the member variables of the class in the above code will be by
default public, hence we can access them as follows:
class Employee:
def __init__(self, name, sal):
self.__name = name # private attribute
self.__sal = sal # private attribute
class Employee:
# constructor
def __init__(self, name, sal):
self._name = name ……….# protected attribute
self._sal = sal …………… # protected attribute
class HR(Employee):
# member function task
def task(self):
print"We manage Employees"
Now let's try to access protected member variable of class Employee from
the class HR:
class Company:
# constructor
def __init__(self, name, proj):
self.name = name # name(name of company) is public
self._proj = proj # proj(current project) is protected
OOPs Concept:
Class
Object
Encapsulation
Data abstraction
Inheritance
Polymorphism
___init___ :-
“___init___” method is reversed method in python class it is called as
constructor in object oriented terminology. This method is called when
object is created from a class and it allows the class to initialize attributes
of class.
Self :
The word “self” is used to represent instance of class by using the
“self” keyword we access the attributes and method of class in python.
Class:
The class is a group of similar entities.
It is only an logical component and not the physical entity.
Class is blueprint, template or prototype of object.
Class is collection of object.
Ex. 1) student
Properties: name, rollno, Date of Birth
Task Performed : raed( ),write( ), play( )
Object:
Object is real world entity that has properties and it perform
different task.
Object is an instance of class.
Ex.
1) Human
Properties: name, color, height
Task perform: walk( ), run( ),read( ),write( )
2) Pen
Properties: Shape, Color
Task perform: write( )
Built-in class attributes
Along with the other attributes, a python class also contains some
built-in class attributes which provide information about the class.
SN Attribute Description
1 __dict__ It provides the dictionary containing the information
about the class namespace.
2 __doc__ It contains a string which has the class
documentation
3 __name__ It is used to access the class name.
Example:
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Python In-built class functions
The in-built functions defined in the class are described in the following
table.
SN Function Description
1 getattr(obj,name,default) It is used to access the attribute of
the object.
2 setattr(obj, name,value) It is used to set a particular value to
the specific attribute of an object.
3 delattr(obj, name) It is used to delete a specific attribute.
Example:
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
s = Student("John",101,22) #creates the object of the class Student
print(getattr(s,'name')) #prints the attribute name of the object s
setattr(s,"age",23) # reset the value of attribute age to 23
print(getattr(s,'age')) # prints the modified value of age
print(hasattr(s,'id')) # prints true if the student contains the attribute with name id
delattr(s,'age') # deletes the attribute age
print(s.age) # this will give an error since the attribute age has been deleted
Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
#Illustration of creating a class
class Student:
'A student class'
stuCount = 0
class Student:
'A student class'
stuCount = 0
def __init__(self): #initialization or constructor method of class
student
self.name=input('enter student name:')
self.rollno=input('enter student rollno:')
Student.stuCount += 1
stu1=Student()
stu2=Student()
stu3=Student()
stu1.displayStudent()
stu2.displayStudent()
stu3.displayStudent()
print('total no. of students:', Student.stuCount)
Encapsulation:
Binding (or wrapping) code and data together into a single unit is
known as encapsulation.
Wrapping of data.
Binding data and function into on single entity.
In python, prevent data from direct modification which is called
encapsulation.
In python, we denote attribute using underscore as prefix
Single underscore ( _ ) for protected
Double underscore ( _ _ ) for private
A class is an example of encapsulation as it encapsulates all the
data that is member functions, variables, etc.
class computer:
def __init__(self):
self.__maxspeed=120
def sell(self):
print("Maximum speed:",self.__maxspeed)
def setter(self,price): #setter function
self.__maxspeed=price
q=computer()
q.sell()
q.__maxspeed=150 # value change but value not change because of encapsulation
q.sell()
q.setter(200) # change value using setter function
q.sell()
Output:
obj1 = Base()
obj2 = Derived()
Output:
Calling protected member of base class:
2
Abstraction :
Abstraction is a process of hiding the implementation details and
Showing only functionality to the user.
Another way, it shows only essential things to the user and hides the
internal details.
for example,
1) Sending SMS where you type the text and send the message. You
don't know the internal processing about the message delivery.
2) Withdraw money from ATM you simply insert card and click some
button and get money but we don’t know their background
process.
Abstract class
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change
the body of the method.
Abstract Method
A method which is declared as abstract and does not have
implementation is known as an abstract method.
To demonstrate abstraction using abstract class
class MobileWalletPayment(Payment):
def payment(self, amount):
print('Mobile wallet payment of- ', amount)
obj = CreditCardPayment()
obj.payment(100)
obj.print_slip(100)
obj = MobileWalletPayment()
obj.payment(200)
obj.print_slip(200)
To demonstrate abstraction
def disp(self):
pass
class Add(A):
def disp(self):
print(self.value)
class Mul(A):
def disp(self):
print(10*self.value)
a=Add(10)
b=Mul(5)
a.disp()
b.disp()
Inheritance:
Inheritance is a mechanism in which one class acquires the property
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.
Single Inheritance:
When a child class inherits from only one parent class, it is called
as single inheritance
Multiple Inheritance:
Multilevel Inheritance :
one class can inherit from a derived class. Hence, the derived class
becomes the base class for the new class.
OR
Hybrid inheritance :
Example:-
1)
add (x, y)
add( )
+ concatenation ( string)
2)
To demonstrate polymorphism
class duck:
def fly(self):
print("duck can't fly")
def swim(self):
print("duck can swim")
class penguin:
def fly(self):
print("penguin can't fly")
def swim(self):
print("penguin can swim")
def flying_test(bird):
bird.fly()
def swiming_test(bird):
bird.swim()
da=duck()
pe=penguin()
flying_test(da)
flying_test(pe)
swiming_test(pe)
swiming_test(da)
To demonstrate polymorphism using for loop
class India():
def capital(self):
print("Delhi is a capital of India")
def language(self):
print("hindi is primary language")
def type(self):
print("india is develeping country")
class USA():
def capital(self):
print("WS is a capital of India")
def language(self):
print("English is primary language")
def type(self):
print("USA is develeped country")
india=India()
usa=USA()
for country in(india,usa):
country.capital()
country.language()
country.type()
#Polymorphism with inheritance
class Bird:
def intro(self):
print("There are many types of birds")
def flight(self):
print("most of birds can fly but some cannot")
class Sparrow(Bird):
def flight(self):
print("sparrow can fly")
class Ostrich(Bird):
def flight(self):
print("ostrich cannot fly")
bird=Bird()
spa=Sparrow()
ost=Ostrich()
bird.intro()
bird.flight()
spa.intro()
spa.flight()
ost.intro()
ost.flight()
Python Operator Overloading
For example,
‘+’ operator which is used with numbers to perform addition operation.
But ‘+’ operator when used with two strings concatenate those Strings and
merge two lists when used with lists in Python. It is possible because ‘+’
operator is overloaded in str and list class to provide extended
functionality.
class complex:
'A complex number class'
def __init__(self, real, imag):
self.real=real
self.imag=imag
def display(self):
print(self.real, "+ i",self.imag)
c1=complex(5,6)
c2=complex(7,8)
c1.display()
c2.display()
c3=c1+c2 #overloading '+' operator call
c3.display()
#Illustration of subtraction '-' operator overloading
class complex:
'A complex number class'
def __init__(self, real, imag):
self.real = real
self.imag = imag
def display(self):
print(self.real, "+ i",self.imag)
c1=complex(5, 8)
c2=complex(6, 7)
c1.display()
c2.display()
c3=c1-c2
c3.display()
#Illustration of relational '>' operator overloading
class distance:
'A distance class'
def __init__(self, a, b):
self.a = a
self.b = b
d1=distance(14, 20)
d2=distance(18, 15)
print(d1>d2)
import math
class Circle:
def get_result(self):
return self.radius
def area(self):
return math.pi * self.radius ** 2
c2 = Circle(15)
print(c2.get_result())
print(c1.area())
c3 = c1 + c2
print(c3.get_result())
c3 = c2 - c1
print(c3.get_result())
c4 = c1 * c2
print(c4.get_result())
c5 = c1 < c2
print(c5.get_result())
c5 = c2 < c1
print(c5.get_result())
Method Overriding
We can provide some specific implementation of the parent class
method in our child class. When the parent class method is defined in
the child class with some specific implementation, then the concept
is called method overriding. We may need to perform method overriding
in the scenario where the different definition of a parent class method is
needed in the child class.
class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;
class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());
Python Constructor
1. Parameterized Constructor
2. Non-parameterized Constructor
Parameterized Constructor :
class Student:
def __init__(self,name,major,gpa):
self.name=name
self.major=major
self.gpa=gpa
def is_on(self):
if self.gpa>3.5:
return Pass
else:
return Fail
s=student(“Vicky”,”xyz”,5.6)
print(s.is_on())
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
Special Function in Python
The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second class,
and false otherwise. Consider the following example.
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
*************Output*************************
True
False
*************************Output*******************
True