Why to learn Object Oriented Programming?
OOP is used in solving real world problems😀. Below are advantages of OOP
- Reusability
- Maintainability
- Easier testing and debugging
- Extensibility
- Improved design
- Modularity
Basics in OOP: Everything in Python is an Object. In Python everything is built by class keyword.
You can see below that how to check if what is the type of any element/thing in Python. You will see everything below has class keyword before it.
Breaking down the program in real world Objects. Objects consists of data and actions. Below are the main four pillars of OOP.
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
A Class is an blueprint of an Object. Whereas Object is collection of data (variables) and methods (functions) that act on those data.
Below is the example of class declaration in Python.
class Employee:
name = "John"
designation = "Engineer"
empid = 12345
Employee is the name of the class and name, designation and empid are the attributes of the class.
Another example:
class Student:
def __init__(self, name, rollno, std):
self.name=name
self.rollno=rollno
self.std=std
print("Name: ", self.name)
print("Roll no: ", self.rollno)
print("STD: ", self.std)
__init__ : This method is like constructor in Python. It will be initialized first by default when an Object for Student class is created.
>>> student1=Student("John", 1, "8th")
Name: John
Roll no: 1
STD: 8th
>>> student2=Student("Jenny", 2, "5th")
Name: Jenny
Roll no: 2
STD: 5th
Blue text shows output after hitting enter in Python IDLE.
Lets now discuss about the four Pillars.
1. Encapsulation: It is the “Bundling” of data and actions into a single unit (class).
- Applied through the principle of information hiding.
- You should restrict direct access to your data unless there is an important reasons not to do so.
- To do this, you can define non-public attributes in Python.
2. Abstraction:
- Different facets and expressions:
- The interface of a component should be independent of the implementation.
- Relying on more general or “abstract” types of objects to avoid code repetition with the use of inheritance
No comments:
Post a Comment