Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
Now Reading
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Imagine you're constructing a complex software system where different classes need to follow a set of rules, ensuring they work harmoniously together. It is where Abstract Base Classes (ABCs) assist. ABC Python is like the architects of your code, defining the blueprint every subclass must adhere to.
In this article, we will look at ABCs, how they vary from regular classes, and understand why they are crucial in object-oriented programming.
An Abstract Base Class (ABC) is a concept in object-oriented programming that serves as a blueprint or template to create classes. It defines a set of methods and attributes implemented by any concrete subclass that inherits from it. Abstract Base Classes are used to enforce a specific interface or contract, ensuring all subclasses adhere to a consistent structure and behavior.
Let us understand what is the purpose of an Abstract class in Python. Abstract Python base class serves several important purposes:
Enforce a Contract: ABC Python defines a contract that subclasses must adhere to. This contract specifies which methods and attributes must be implemented by any concrete subclass and gives consistency and correctness in the codebase.
Provide a Common Interface: ABCs define a common set of methods used uniformly across different subclasses. It allows code to be more generic and flexible, as it can work with any class that conforms to the ABC.
Documentation and Guidance: ABCs serve as documentation for the expected behavior of subclasses. Developers can see which methods must be implemented and make it easier to understand and extend the codebase.
Polymorphism and Type Safety: They enable polymorphism, simplifying code reusability and type checking by ensuring shared methods and attributes among objects.
Error Prevention and Validation: ABCs detect errors during design by verifying concrete subclasses implement all required methods and reduce runtime issues.
Let's illustrate this with an example in ABC Python:
code
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
Here, Shape is an abstract base class with an abstract method in the Python example area(). Circle and Rectangle are concrete subclasses of Shape, and they implement the area() method as required.
Abstract Base Classes define a class hierarchy in which some methods are marked as abstract using the @abstractmethod decorator. Subclasses must implement these abstract methods to be considered valid.
In Python, you need to import the ABC class and the abstractmethod decorator from the abc module.
Here's a breakdown of how they work:
To implement an abstract Python base class through subclassing, follow these steps:
Abstract base classes can contain abstract methods and concrete (non-abstract) methods. Concrete methods provide a default implementation that subclasses can override but is not mandatory.
Here's an abstract method in Python example:
code
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass
def stop_engine(self):
print("Engine stopped")
class Car(Vehicle):
def start_engine(self):
print("Car engine started")
# Create an instance of Car
car = Car()
car.start_engine() # Output: Car engine started
car.stop_engine() # Output: Engine stopped
In this example, Vehicle is an abstract Python base class with an abstract method start_engine() and a concrete method stop_engine(). The Car subclass implements the start_engine() method but inherits the stop_engine() method.
Abstract properties are attributes defined in an abstract base class that must be implemented as properties (getter and/or setter methods) by subclasses. You can use the @property decorator to define abstract properties.
Example of Python abstract class property:
code
from abc import ABC, abstractmethod
class Shape(ABC):
@property
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14 * self._radius * self._radius
class Rectangle(Shape):
def __init__(self, length, width):
self._length = length
self._width = width
@property
def area(self):
return self._length * self._width
Shape is an abstract base class with a Python abstract class property area in this example. Circle and Rectangle are concrete subclasses of Shape that implement the area property.
Abstract base classes cannot be instantiated directly. You can only create instances of concrete subclasses. Attempting to create an instance of an abstract base class will raise a TypeError.
Example:
code
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
# Attempt to create an instance of the abstract base class
animal = Animal() # This will raise a TypeError
In this example, trying to create an instance of the abstract base class Animal results in an error. You must create instances of concrete subclasses like Dog or Cat instead.
Abstraction in Python is important in programming for several reasons:
1. Encapsulation: Abstraction in Python allows you to hide the internal details of an object and expose only what is necessary. This promotes encapsulation, a fundamental principle of object-oriented programming.
Example:
In a banking application, you can abstract a BankAccount class to encapsulate the details of an account while providing methods like deposit and withdrawal for interaction.
2. Code Reusability: Abstract base classes provide a blueprint for creating subclasses with shared behavior. This promotes code reusability and reduces duplication.
Example:
In a game development framework, an abstract GameObject class can define methods like update and render that all game objects must implement.
3. Maintenance and Extensibility: Abstraction in Python makes maintaining and extending your code easier. When you need to make changes, you can focus on the abstract interface, knowing that all subclasses will follow the same contract.
Example:
Adding new shapes to a drawing application becomes straightforward when you have an abstract Shape class that defines methods like area and draw.
4. Design Patterns: Abstraction is a fundamental concept in many design patterns, such as the Factory Method, Strategy, and Observer patterns. These patterns rely on abstract base classes to achieve flexibility and modularity.
Example:
The Strategy pattern uses abstract classes to define interchangeable algorithms that can be used in different contexts.
Abstract classes work by defining a contract that subclasses must adhere to. They provide a blueprint for creating related classes with a standard interface and shared behavior. Here's how they work:
You typically use the ABC (Abstract Base Class) module and the @abstractmethod decorator to create an abstract class in Python. An abstract class is defined by subclassing ABC Python and declaring one or more abstract methods using the @abstractmethod decorator.
code
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
def concrete_method(self):
print("This is a concrete method.")
In this example, AbstractClass is an abstract class in Python with an abstract method abstract_method() and a concrete method concrete_method().
Concrete subclasses are classes that inherit from the abstract class in Python and provide implementations for the abstract method in Python defined in the abstract class.
code
class ConcreteClass(AbstractClass):
def abstract_method(self):
print("Implemented abstract_method in ConcreteClass.")
def additional_method(self):
print("This is an additional method.")
Here, ConcreteClass is a concrete subclass of AbstractClass, and it provides an implementation for the abstract_method().
You cannot create an instance of an abstract class in Python directly. Attempting to do so will result in a TypeError. You can only create instances of concrete subclasses.
code
# Attempting to create an instance of the abstract class
# This will raise a TypeError
abstract_instance = AbstractClass()
# Creating an instance of the concrete subclass
concrete_instance = ConcreteClass()
In this example, abstract_instance = AbstractClass() will raise a TypeError, but concrete_instance = ConcreteClass() is valid.
Polymorphism allows you to work with objects of different subclasses through a common interface. Since the abstract class and its concrete subclasses adhere to the same interface, you can use polymorphism to interact with them uniformly.
code
def use_abstract_class(instance):
instance.abstract_method()
instance.concrete_method()
# Using the abstract class and its concrete subclass
use_abstract_class(concrete_instance)
In this example, the use_abstract_class function can take either an instance of the abstract class or its concrete subclass, and it calls abstract_method() and concrete_method().
Abstract classes enforce a contract by ensuring that all concrete subclasses provide implementations for the abstract methods. If a concrete subclass doesn't implement all the abstract methods, it will be considered abstract and cannot be instantiated.
Code
class IncompleteConcreteClass(AbstractClass):
def concrete_method(self):
print("Implemented concrete_method in IncompleteConcreteClass.")
# Attempting to create an instance of an incomplete concrete class
incomplete_instance = IncompleteConcreteClass()
In this example, IncompleteConcreteClass does not implement abstract_method(), so to create an instance of it will raise a TypeError.
In this example, we'll create an abstract class in Python called Shape with abstract methods for calculating area and perimeter. Then we'll create concrete subclasses to implement these methods for specific shapes such as circles and rectangles.
code
from abc import ABC, abstractmethod
import math
# Step 1: Define an abstract class 'Shape'
class Shape(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def calculate_area(self):
pass
@abstractmethod
def calculate_perimeter(self):
pass
def display_info(self):
print(f"Shape: {self.name}")
print(f"Area: {self.calculate_area()}")
print(f"Perimeter: {self.calculate_perimeter()}")
# Step 2: Create concrete subclasses
# Subclass 1: Circle
class Circle(Shape):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
def calculate_area(self):
return math.pi * self.radius ** 2
def calculate_perimeter(self):
return 2 * math.pi * self.radius
# Subclass 2: Rectangle
class Rectangle(Shape):
def __init__(self, name, length, width):
super().__init__(name)
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
def calculate_perimeter(self):
return 2 * (self.length self.width)
# Step 3: Create instances of concrete subclasses
circle = Circle("Circle 1", 5)
rectangle = Rectangle("Rectangle 1", 4, 6)
# Step 4: Use the abstract class methods
circle.display_info()
print("--------------------------")
rectangle.display_info()
Abstract Base Classes design object-oriented programs that emphasize encapsulation, reusability, and maintainability. By defining abstract methods, properties, and classes, you can create a clear structure for your code and ensure subclasses have a common interface.
This guide has provided an all-around overview of Abstract Classes in Python and their importance in programming using real-world examples and practical explanations. Using abstraction, programmers can make robust and flexible codebases and make software development projects more successful.
1. Can you have concrete methods in an abstract base class?
Yes, you can have concrete (non-abstract) methods in an abstract base class. These methods provide default behavior overridden by subclasses but are not mandatory.
2. Is it possible to inherit from multiple abstract base classes in Python?
Yes, Python supports multiple inheritance, which means you can inherit from multiple abstract base classes. However, be careful when dealing with potential conflicts in method names and behaviors.
3. Can I define abstract properties in an ABC?
Yes, you can define abstract properties in an ABC using the @property decorator. Subclasses must provide the getter and/or setter methods for these properties.
4. Are abstract base classes specific to Python?
No, abstract base classes are not specific to Python. They are a concept found in many object-oriented programming languages, although the implementation details may vary.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...