Python OOPS – Introduction
OOPS (Object-Oriented Programming System) is a way of writing programs using objects. An object is a thing that has some data (properties) and some actions (methods). For example, a car has a brand and a colour, and it can start or stop.
Python supports object-oriented programming, and almost everything in Python is an object, like strings, lists and even functions.
Main concepts of OOPS
| Concept | Meaning |
|---|---|
| Class | A blueprint or template to create objects |
| Object | A real thing created from a class |
| Method | A function that belongs to a class or object |
| Inheritance | A class takes the features of another class |
| Polymorphism | The same name works in different ways |
| Encapsulation | Keeping data and methods together and controlling access to the data |
| Abstraction | Showing only what is needed and hiding the details |
Class and object
Think of a class as a plan of a house, and objects as the real houses built from that plan. One class can create many objects.
class Car:
def __init__(self, brand):
self.brand = brand
def start(self):
print(self.brand, "is starting")
car1 = Car("Tata")
car2 = Car("Honda")
car1.start()
car2.start()
Tata is starting
Honda is starting
Car is the class. car1 and car2 are two objects, each with its own brand. Learn this in detail in Python Classes and Objects, and about functions of a class in Python Object Methods.
The four pillars
1. Inheritance
A child class can use the code of a parent class, so you do not write it again. See Python Inheritance.
2. Polymorphism
The same method name can behave differently for different classes. See Polymorphism in Python.
3. Encapsulation
Data and the methods that use the data are kept in one class. Some data can be made private so that outside code cannot change it directly. See Python Access Modifiers.
4. Abstraction
Abstraction means hiding the inside details and showing a simple way to use something. You drive a car with a steering wheel and pedals, without knowing how the engine works. In Python it is done with classes and methods, and with the abc module for abstract classes.
Why use OOPS?
- Code is easier to organize in big programs.
- Code can be reused with inheritance.
- Data is safer with encapsulation.
- Real world things are easy to model.
Summary
- OOPS builds programs from objects created from classes.
- The main ideas are class, object, method, inheritance, polymorphism, encapsulation and abstraction.
- Continue with Python Classes and Objects.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |