In the this article, we learnt OOP concepts in Java. In this article we are going to see what Object Oriented Programming in another programming language, Python. Object-Oriented Programming is a programming paradigm that organizes data around the idea of objects. We can define an object as a real-world entity that has attributes and behaviors. In Object-Oriented Programming, there are terms that we need to get familiar with so as to understand the whole idea behind OOP. These terms are "class", "object", "attributes” and “methods”. Code with OOP design is flexible, modular, and abstract. This makes it particularly useful when you create larger programs.
A class is a blueprint that defines how an object should be implemented whereas an object is an instance of a class. We can define many objects from a single class as long as they are related.
Attributes are the information that is stored in a class. When a class object is instantiated, individual objects contain information that is stored in attributes. Methods define behaviors that objects should have. These objects might return some information or update an object's data.
Benefits of Object-Oriented Programming
i) Re-usability - OOP objects are reusable across the whole program.
ii) Code maintenance - It is always easy and time-saving to maintain and modify the existing codes by incorporating new changes into them.
iii) Security - With the use abstraction mechanism, we are exposing only the data that we need the user to see which means we are maintaining security.
iv) OOP benefits the programmer by providing a better design structure. By this, the programmer is saved from making mistakes and writing bad code.
v) Easier troubleshooting – When something goes wrong, you know exactly where to look at it. For instance, when a car object breaks, you know that there is a problem with the car class.
Principles of Object-Oriented Programming
In this post, we are going to look at the principles of OOP one by one using Python programming. Many programming languages also support this paradigm including Java, PHP, JavaScript, C++, and many more.
Inheritance
It is the ability of a class to derive properties and characteristics from another class. Note: The class that inherits properties from another class is called subclass/derived class whereas the class whose properties are inherited is called class/base class.
As we saw before, the primary benefit of inheritance is code re-usability, therefore saving time on programming. Python supports four different types of inheritance. Types of Inheritance depend upon the number of child and parent classes involved.
Single Inheritance
Single inheritance enables a derived class to inherit properties from a single parent class. This following is an example of a Python program to demonstrate single inheritance.
# Parent class
class Dog:
def function1(self):
print("I'm a function from parent class!")
# Child class
class Bulldog(Dog):
def function2(self):
print("I'm a function from child class!")
# Driver code
object1 = Bulldog()
object1.function1()
object1.function2()
The following is the output of our program:
I'm a function from parent class!
I'm a function from child class!
Multiple Inheritance
This is where a subclass can inherit from more than one superclass. This following is an example of a Python program to demonstrate multiple inheritances.
# Parent class1
class Donkey:
donkey_name = ""
def father(self):
print(self.donkey_name)
# Parent class2
class Horse:
horse_name = ""
def mother(self):
print(self.horse_name)
# Child class
class Child(Donkey, Horse):
def parents(self):
print("Father : ", self.donkey_name)
print("Mother : ", self.horse_name)
# Driver code
c1 = Child()
c1.donkey_name= "Jack"
c1.horse_name = "Mare"
c1.parents()
The following is the output of our program:
Father: Jack
Mother: Mare
Multilevel Inheritance
Here, one class can inherit from another class which also inherits from another class. Let’s look at this example to demonstrate multilevel inheritance.
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
# invoking constructor of Grandfather class
Grandfather.__init__(self, grandfathername)
# Derived class
class Son(Father):
def __init__(self,sonname, fathername, grandfathername):
self.sonname = sonname
# invoking constructor of Father class
Father.__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
The following is the output of our program:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Hierarchical Inheritance
This is where more than one sub-class can be derived from the same superclass. Example of a Python program to demonstrate Hierarchical inheritance.
# Base class
class Parent:
def function1(self):
print("This is function 1")
# Child class1
class Child1(Parent):
def function2(self):
print("This is function 2")
# Child class2
class Child2(Parent):
def function3(self):
print("This is function 3")
# Driver code
ob = Child1()
ob1 = Child2()
ob.function1()
ob.function2()
Output:
This is function 1
This is function 2
Abstraction
Abstraction is a another feature of Object Oriented Programming that displays only essential details to the user while hiding the implementation details. The concept of abstraction makes the application to be presented to the user in the simplest way possible.
In Python, abstraction can be achieved by using abstract classes and methods in our programs. Example of a Python program to demonstrate abstraction.
From abc import ABC
#abstract class
class Shape(ABC):
def calculate_area(self): #abstract method
pass
class Rectangle(Shape):
length = 5
breadth = 3
def calculate_area(self):
return self.length * self.breadth
class Circle(Shape):
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
rec = Rectangle() #object created for the class 'Rectangle'
cir = Circle() #object created for the class 'Circle'
#call to 'calculate_area' method defined inside the class 'Rectangle'
print("Area of a rectangle:", rec.calculate_area())
#call to 'calculate_area' method defined inside the class 'Circle'.
print("Area of a circle:", cir.calculate_area())
The following is the output:
Area of a rectangle: 15
Area of a circle: 50.24
Encapsulation
It is defined as wrapping up of data and information under a single unit. In other words, it is defined as binding together the data and the functions that manipulate them. Example of a Python program to demonstrate protected members
# Creating a base class
class Base:
def __init__(self):
# Protected member
self._a = 2
# Creating a derived class
class Derived(Base):
def __init__(self):
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ")
print(self._a)
# Driver code
obj1 = Derived()
obj2 = Base()
# Calling protected member
# Outside class will result in
# AttributeError
print(obj2.a)
The following is the output:
AttributeError: 'Base' object has no attribute 'a'
Polymorphism
It is an Object Oriented Programming concept that refers to the ability of variables, functions or objects to take or occur in many forms. Example of a Python program to demonstrate polymorphism.
class Kenya():
def capital(self):
print("Nairobi")
def language(self):
print("Kiswahili and English")
class Britain():
def capital(self):
print("London")
def language(self):
print("English")
obj_kenya = Kenya()
obj_britain = Britain()
for country in (obj_kenya, obj_britain):
country.capital()
country.language()
Output:
Nairobi
Kiswahili and English
London
English
In this example, the function "capital" and "language" are used in the two classes "Kenya" and "Britain" but they are returning different results. This is an of polymorphism in class functions.
Conclusion
We have looked at Object-Oriented Programming, its benefits, and some various examples in Python language. I hope this post has given you a foundation in OOP and Python language. Feel free to look at some examples and practice on your own to sharpen your skills.
Did you like my article? Please share it using these buttons. Thanks!