Introduction to OOPs in Python

What Is Object-Oriented Programming (OOP)?

Object-oriented Programming, or OOP, in short, is a programming paradigm that helps in structuring programs so that the properties and behaviors are bundled into individual objects. For instance, an object could represent a person with properties such as age, name, address, etc., with behaviors such as walking, talking and running.

Class:

Classes provide a means of bundling data and functionality together by defining blueprint/skeleton for the object.

Syntax:

a2

Object:

An object is an instantiation of a class. When class is defined, only the description for the object is defined. But when an object is created then memory or storage is allocated is also allocated.

Syntax:

a1

Class and Object Example:

a3

The above example has a class name ‘Apple’, with three different components.

1.      Class Attributes: These are attributes that are shared across all the objects.

2.      Instance Attributes: These are attributes that hold the properties of the objects. They are different for different objects.

3.      Methods: These hold the logic that defines the behavior of an object.

The above example also creates two objects, app1 and app2 having a respective name and color property. Separate memory gets allocated to two of the objects.

 

Inheritance:

Inheritance enables new objects to get the properties of existing objects. A class that is used as the base for inheritance is called a superclass or base class. A class that inherits from a superclass is called a subclass or derived class.

 

a7

output:

a6

 

In the above example, ‘Fruit’ is the base class and ‘Apple’ is the child class. Even though a color method is not present in the Apple class, it gets inherited from the base class Fruit.

Note: super is the keyword used to call parent class constructor in python. When the apple object is initialized, first the parent constructor is called and then the child constructor gets called.

 

Encapsulation:

Encapsulation is an Object-Oriented Programming concept that binds together the data and functions that applies to the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.

25

Output:

a4

In the above example, size is a private property which can be modified only by the methods within that class. When the variable is tried to update the value outside of the class then action has no effect and value remains unchanged.

 

 

 

 

 

 

 

Leave a comment