Abstraction in Python

Abstraction in Python, Object-Oriented Programming Principes in Python, Inheritance, Polymorphism, Data Abstraction, and Encapsulation.

Data Abstraction in Python

What is Abstraction?

Abstraction is one of the most important features of object-oriented programming. It is used to hide the implementation details.

In Python, we can achieve abstraction by incorporating abstract (incomplete) classes and methods.

Any class that contains an abstract (incomplete) method is called an abstract class.

Abstraction classes

In Python, abstraction can be achieved by using abstract classes and interfaces.

A class that consists of one or more abstract methods is called the abstract class. Abstract methods do not contain their implementation. An abstract class can be inherited by the subclass and the abstract method gets its definition in the subclass.

Example:

class Bikes:

def wheels(self):
pass

def handle(self):
print (“Bikes have Handle”)

def engine(self):
pass

class HeroHonda(Bikes):

def wheels(self):
print (“Bikes have Spoke Wheels”)

def engine(self):
print (“Bikes have 4TX Engine”)

myobject=HeroHonda()
myobject.handle()
myobject.engine()
myobject.wheels()

print(“”)

class Bajaj(Bikes):

def wheels(self):
print (“Bikes have Alloy Wheels”)

def engine(self):
print (“Bikes have FT7 Engine”)

myobject=Bajaj()
myobject.handle()
myobject.engine()
myobject.wheels()


Access Modifiers in Python

The access modifiers in Python are used to modify the default scope of variables. There are three types of access modifiers in Python: public, private, and protected.

Variables with the public access modifiers can be accessed anywhere inside or outside the class, the private variables can only be accessed inside the class, while protected variables can be accessed within the same package.

class Car:
def __init__(self):
print (“Engine started”)
self.name = “Wegnar”
self.__make = “Maruthi”
self._model = 1999

What is Encapsulation in Python?

Encapsulation in Python describes the concept of bundling data and methods within a single unit.

Accessing private fields via methods

class Car:
def __init__(self):
print (“Engine started”)
self.name = “Wegnar”
self.__make = “Maruthi”
self._model = 1999
def myvar(self):
return self.__make

class myCar(Car):
abc=123

obj = myCar()
x = obj.abc
print(x)
x = obj.name
print(x)

x = obj.myvar()
print(x)


Python Tutorial
Python Videos
Follow me on social media: