OOPs In Python
What is OOPs?
OOPs simply means Object Oriented Programming.
It is a Fundamental Concept in Programming Languages like Python
, Java
,JavaScript
, C
, C++
etc.
Definition :
Object Oriented Programming
(oops) concept is a technique/pattern that uses Objects
and Classes
to implement real-world entities like inheritance ,polymorphism ,encapsulation etc.
Now, let's get to know this opps concepts with python one by one.
OOPs Concepts in Python
Objects
Inheritance
Polymorphism
Encapsulation
Abstraction
Class
A class is a collection of objects.
Contains a blueprint on which objects are being created.
A logical entity that contains attributes/properties and methods/functions.
attributes
are variables that belong to a class, they are always kept public.
methods
are class functions within the class
how to create a class in python?
We Create a Class using a "class" keyword in python, followed by giving a name using CamelCase naming convention.
Let's Create an Empty Class
class MyFirstClass: #MyFirstClass is name of the class
pass
Objects
Object are nothing but , Instance of a class. An Entity that has a State and a Behavior associated with it.
State
refers to the attributes of an object.
Behavior
refers to the actions that object can take through methods/functions.
how to create a object in python?
Object Cannot be create without a Class in python programming. So let's use the class we create earlier.
obj = MyFirstClass() #instantiation / initialization of object
Here we first, initialized out object with variable "obj". Now "obj" is the name of our object like wise we can create many object from a same class.
obj1 = MyFirstClass()
obj2 = MyFirstClass()
...
objn = MyFirstClass()
The Python "self "
Class methods must have an extra first parameter in the method
definition or arguments.
Let's create some attributes and methods in our class.
class MyFirstClass: #MyFirstClass is name of the class
#Class Attributes
city = "Mumbai"
country = "India"
#Class Methods
def about(self,name): #self is required to be mentioned
return f"Hi,I am {name} from {self.city}, {self.country}"
Let's Create an object.
obj = MyFirstClass() #instantiation /initialization of object
Accessing Class Attributes and printing it.
obj.city
obj.country
print("City:", obj.city)
print("Country:", obj.country)
Output
:
City: Mumbai
Country: India
Accessing Methods
show = obj.about("Tejas") #passing arguments
print("About me:",show)
About me: Hi,I am Tejas from Mumbai, India.
The Python "__init__" Method
The init method in python is like constructor in C++ and Java.
It runs as soon as the object of the class is instantiated.
class MyFirstClass: #MyFirstClass is name of the class
#Class Attributes
city = "Mumbai"
country = "India"
#python constuctor
def __init__(self,skill):
self.skill = skill
#Class Methods
def about(self,name):
return f"Hi,I am {name} from {self.city}, {self.country}
skilled in {self.skill}."
#..rest.. same code>>
Accessing Instance Attributes
obj = MyFirstClass("Python")
show = obj.about("Tejas")
print("About me:",show)
print(obj.skill) #Accessing Instance Attributes
About me: Hi,I am Tejas from Mumbai, India skilled in Python.
Python
Inheritance
Inheritance in a phenomenon in which one class can be derive / inherit the properties from another class.
child class
: a class that derives property from another class is called a derived class or child class.
parent class
: the class from which the properties are being derived is called base or parent class.
Example : 1] A son inherits the genetical properties of his Dad.
2] Daughter inherits genetical properties of Mother.
The benefits of inheritance are ?
Code reusability : We don’t have to write the same code again and again.
Inheritance in python
Python Inheritance Syntax :
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Now , let's dive into some practical coding.
Creating Parent Class
class Person:
def __init__(self,name,weight,height):
self.name = name
self.weight = weight
self.height = height
def PersonInfo(self,personID):
personID = personID
print(f"ID no. {personID} : Hi my name is {self.name} {self.lastname},\n my school name is {self.school_name} \n and my weight is {self.weight} & height is {self.height}.\n I study {','.join(self.subjects)} in my school.")
Creating a Child Class
class Student(Person):
def __init__(self,subjects,school_name,name, weight,height):
self.subjects= subjects
self.school_name = school_name
Person.__init__(self, name, weight,height)
# invoking the __init__ method of the parent class
def PersonInfo(self,personID):
Person.PersonInfo(self,personID)
# invoking the PersonInfo method of the parent class
Object Creation
#Object Creation
subjects = ['math','science','geographgy']
school_name = "ies vikarant"
name = 'Tejas'
weight = '82 Kg'
height = '6.1'
stu = Student(subjects,school_name,name,weight,height)
show = stu.PersonInfo(210)
Output
ID no. 210 : Hi my name is Tejas , my school name is IES Vikarant and my weight is 82 Kg & height is 6.1. I study math,science,geographgy in my school.
Forget Superman we have "super()" Function
The super() function is a built-in function that returns the objects that represent the parent class.
Instead of Specifying name of the parent class just mention super() and don't declare self in it.
It is commonly used to invoke the parent class’s__init__
method from the child class to ensure proper initialization.
class Student(Person):
def __init__(self,subjects,school_name,name, weight,height):
self.subjects= subjects
self.school_name = school_name
super().__init__(name, weight,height)
# invoking the __init__ method of the parent class
def PersonInfo(self,personID):
Person.PersonInfo(self,personID)
# invoking the PersonInfo method of the parent class
Types of Inheritance
Single Inheritance:
Single-level inheritance enables a child class to inherit characteristics from a single-parent class which we just saw above.
Multiple Inheritance
Multiple-level inheritance is one child class inherits properties from more than one parent/base class.
Structure :
class Parent1: pass class Parent2: pass class Child(Parent1, Parent2): pass
Let's Create an another class :
class Son: def __init__(self,lastname): self.lastname = lastname
Now ,add this to our child class :
Note: Making a small change , adding print to PersonInfo() method of Student class instead of Person class.
class Student(Person,Son): #Take Multiple Parent Classes def __init__(self,subjects,school_name,name, weight,height,lastname): self.subjects= subjects self.school_name = school_name Person.__init__(self, name, weight,height) # invoking the __init__ of the parent class Person Son.__init__(self,lastname) # invoking the __init__ of the parent class Son def PersonInfo(self,personID): Person.PersonInfo(self,personID) print(f"ID no. {personID} : Hi my name is {self.name} {self.lastname} \n , my school name is {self.school_name} \n and my weight is {self.weight} & height is {self.height}.\n I study {','.join(self.subjects)} in my school.")
Multilevel Inheritance
Multi-level inheritance is when a child class inherit properties from an immediate parent class which in turn inherits properties from his parent class.
Example : Son inherits genetics properties of his Father as well of his Grandfather.
Here, class Person is inherited my class Son and
Structure :
class Grandparent: pass class Parent(Grandparent): pass class Child(Parent): pass
class Son(Person): def __init__(self,lastname,name, weight,height): self.lastname = lastname Person.__init__(self, name, weight,height)
Class Son is inherited by Class Student rest same.
class Student(Son): def __init__(self,subjects,school_name,name, weight,height,lastname): self.subjects= subjects self.school_name = school_name # invoking the __init__ of the parent class Son.__init__(self,lastname) def PersonInfo(self,personID): Person.PersonInfo(self,personID)
ID no. 210 : Hi my name is Tejas Coder, my school name is IES Vikarant and my weight is 82 Kg & height is 6.1. I study math,science,geographgy in my school.
Hierarchical Inheritance: Hierarchical-level inheritance is when multiple child classes inherits properties from a same parent class.
Structure :
class Parent: pass class Child1(Parent): pass class Child2(Parent): pass
Class Student is already there which inherits Class Person.
Now, let's create a another child class that inherits Class Person.
class Coder(Person): def __init__(self,prog_lang,skill, weight,height,lastname): self.prog_lang = prog_lang self.skill = skill Person.__init__(self,name, weight,height) # invoking the __init__ of the parent class def PersonInfo(self): print(f"Hi my name is {self.name} I am skill in {self.skill} using {self.prog_lang} programming language")
**Hybrid Inheritance:**A combination of two or more types of inheritance.
Polymorphism
Polymorphism Simply means many forms.
poly
means many.
morph
means forms.
Polymorphism refers to the methods/functions with the same name that can be executed on many objects or classes.
For Example : 1] A same Person can be a Employee ,Father, Son and Husband ,etc.
3] len()
function in python.
len()
can be applied on string, list , tuple, dictionary etc. to count the length.
3] A human speaks , Dog barks, Cat meow's and a bird tweets this all can be considered in a talking part.
Likewise , we can use same method/function for various purposes using method overriding.
class Speak: #main class
def __init__(self,name):
self.name = name
def talk(self):
print(self.name,": Speaks Hello")
-
class Cat(Speak):
def talk(self):
print(self.name,":Meow!") #talk() method is mentioned here so python will override it.
class Person(Speak):
pass #talk not here so,python will search talk() method in parent class.
class Dog(Speak):
def talk(self):
print(self.name,":Bark")
#object creation
cat = Cat("kitty")
cat.talk()
person = Person("Tejas")
person.talk()
dog = Dog("Tommy")
dog.talk()
Here, in class Cat & Dog talk()
method is mentioned so python will override it.
In Class Person , either talk()
nor __init__
method is present so, python will search them it's in parent class.
kitty :Meow!
Tejas : Speaks Hello
Tommy :Bark
Encapsulation
Encapsulation is the idea of wrapping data and the methods together within one unit.
Encapsulation helps to protect the data by putting restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
Example : A Capsule Containing Multi-Medicine.
Encapsulation in Python
Access Modifiers
# public data member
var1 = None
# protected data member
_var2 = None
# private data member
__var3 = None
Keeping Access Modifiers Private we can achieve encapsulation in python.
class Encap:
def __init__(self):
self.pu = "Hi , hru" #public member of class
self.__privt = "Hi, i am private"
#private member of classen = Encap()
#object Creation
en = Encap()
print(en.pu)
Hi , hru
Trying To access private class members from outside.
print(en.__privt)
Traceback (most recent call last):
File "C:\Users\tejas\Desktop\My Env\Rough Episodes\Rough Path\encap.py", line 9, in <module>
print(en.__privt)
^^^^^^^^^^
AttributeError: 'Encap' object has no attribute '__privt'
print(en.privt)
Traceback (most recent call last):
File "C:\Users\tejas\Desktop\My Env\Rough Episodes\Rough Path\encap.py", line 9, in <module>
print(en.privt)
^^^^^^^^
AttributeError: 'Encap' object has no attribute 'privt'
here ,variable privt is private so cannot be accessed outside the class nor by the child class. BUT can be accessed within the class.
class Child(Encap):
def display(self):
print(self.pu)
print(self.__privt)
ch = Child()
ch.display()
Hi , hru
Traceback (most recent call last):
File "C:\Users\tejas\Desktop\My Env\Rough Episodes\Rough Path\encap.py", line 16, in <module>
ch.display()
File "C:\Users\tejas\Desktop\My Env\Rough Episodes\Rough Path\encap.py", line 9, in display
print(self.__privt)
^^^^^^^^^^^^
AttributeError: 'Child' object has no attribute '_Child__privt'
Accessing within the class
class Encap:
def __init__(self):
self.pu = "Hi , hru"
self.__privt = "Hi, i am private"
def display(self):
print(self.__privt)
en = Encap()
# print(en.pu)
# print(en.__privt)
en.display()
Hi, i am private
Abstraction
Abstraction is the concept of hiding complex logic / implementation and showing only the essential features of an object.
Example : A mobile Phone hides complex hardware and software section and only show case user friendly essential features.
In python abstraction is not explicitly implemented.
We can use abc library or @abstractmethod decorator for it.
from abc import ABC, abstractmethod
class Car(ABC): #abstract class is python
@abstractmethod #abstract method
def mileage(self):
pass
class Tesla(Car):
def mileage(self):
print("Mileage is 40 km")
class Audi(Car):
def mileage(self):
print("Mileage is 30 km")
class Tata(Car):
def mileage(self):
print("Mileage is 50 km")
T = Tesla()
A = Audi()
t = Tata()
T.mileage()
A.mileage()
t.mileage()
Mileage is 40 km
Mileage is 30 km
Mileage is 50 km
Note:
- An Abstract class can contain the both method normal and abstract method.
class Car(ABC): #abstract class is python
@abstractmethod #abstract method
def mileage(self):
pass
#normal method
def display():
print("Car")
- An Abstract cannot be instantiated; we cannot create objects for the abstract class.
c = Car()
Traceback (most recent call last):
File "C:\Users\tejas\Desktop\My Env\Rough Episodes\Rough Path\abs.py", line 28, in <module>
c = Car()
^^^^^
TypeError: Can't instantiate abstract class Car with abstract method mileage
Going Great !
Will See You In Next Part
Subscribe to my newsletter
Read articles from Tejas More directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by