{"id":180,"date":"2024-01-25T14:56:25","date_gmt":"2024-01-25T14:56:25","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=180"},"modified":"2024-01-25T14:56:26","modified_gmt":"2024-01-25T14:56:26","slug":"python-abstract-classes","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/25\/python-abstract-classes\/","title":{"rendered":"Python Abstract Classes"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about Python Abstract classes and how to use it to create a blueprint for other classes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to Python Abstract Classes<\/h2>\n\n\n\n<p>In object-oriented programming, an abstract class is a\u00a0class\u00a0that cannot be instantiated. However, you can create classes that inherit from an abstract class.<\/p>\n\n\n\n<p>Typically, you use an abstract class to create a blueprint for other classes.<\/p>\n\n\n\n<p>Similarly, an abstract method is an method without an implementation. An abstract class may or may not include abstract methods.<\/p>\n\n\n\n<p>Python doesn\u2019t directly support abstract classes. But it does offer a\u00a0module\u00a0that allows you to define abstract classes.<\/p>\n\n\n\n<p>To define an abstract class, you use the&nbsp;<code>abc<\/code>&nbsp;(abstract base class) module.<\/p>\n\n\n\n<p>The&nbsp;<code>abc<\/code>&nbsp;module provides you with the infrastructure for defining abstract base classes.<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from abc import ABC class AbstractClassName(ABC): pass <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To define an abstract method, you use the\u00a0<code>@abstractmethod<\/code>\u00a0decorator:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from abc import ABC, abstractmethod class AbstractClassName(ABC): @abstractmethod def abstract_method_name(self): pass <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Python abstract class example<\/h2>\n\n\n\n<p>Suppose that you need to develop a payroll program for a company.<\/p>\n\n\n\n<p>The company has two groups of employees: full-time employees and hourly employees. The full-time employees get a fixed salary while the hourly employees get paid by hourly wages for their services.<\/p>\n\n\n\n<p>The payroll program needs to print out a payroll that includes employee names and their monthly salaries.<\/p>\n\n\n\n<p>To model the payroll program in an object-oriented way, you may come up with the following classes:&nbsp;<code>Employee<\/code>,&nbsp;<code>FulltimeEmployee<\/code>,&nbsp;<code>HourlyEmployee<\/code>, and&nbsp;<code>Payroll<\/code>.<\/p>\n\n\n\n<p>To structure the program, we\u2019ll use\u00a0modules, where each class is placed in a separate module (or file).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Employee class<\/h3>\n\n\n\n<p>The&nbsp;<code>Employee<\/code>&nbsp;class represents an employee, either full-time or hourly. The&nbsp;<code>Employee<\/code>&nbsp;class should be an abstract class because there\u2019re only full-time employees and hourly employees, no general employees exist.<\/p>\n\n\n\n<p>The&nbsp;<code>Employee<\/code>&nbsp;class should have a property that returns the full name of an employee. In addition, it should have a method that calculates salary. The method for calculating salary should be an abstract method.<\/p>\n\n\n\n<p>The following defines the\u00a0<code>Employee<\/code>\u00a0abstract class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from abc import ABC, abstractmethod class Employee(ABC): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def full_name(self): return f\"{self.first_name} {self.last_name}\" @abstractmethod def get_salary(self): pass <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">The FulltimeEmployee class<\/h3>\n\n\n\n<p>The&nbsp;<code>FulltimeEmployee<\/code>&nbsp;class inherits from the&nbsp;<code>Employee<\/code>&nbsp;class. It\u2019ll provide the implementation for the&nbsp;<code>get_salary()<\/code>&nbsp;method.<\/p>\n\n\n\n<p>Since full-time employees get fixed salaries, you can initialize the salary in the constructor of the class.<\/p>\n\n\n\n<p>The following illustrates the\u00a0<code>FulltimeEmployee<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class FulltimeEmployee(Employee): def __init__(self, first_name, last_name, salary): super().__init__(first_name, last_name) self.salary = salary def get_salary(self): return self.salary <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">The HourlyEmployee class<\/h3>\n\n\n\n<p>The&nbsp;<code>HourlyEmployee<\/code>&nbsp;also inherits from the&nbsp;<code>Employee<\/code>&nbsp;class. However, hourly employees get paid by working hours and their rates. Therefore, you can initialize this information in the constructor of the class.<\/p>\n\n\n\n<p>To calculate the salary for the hourly employees, you multiply the working hours and rates.<\/p>\n\n\n\n<p>The following shows the\u00a0<code>HourlyEmployee<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class HourlyEmployee(Employee): def __init__(self, first_name, last_name, worked_hours, rate): super().__init__(first_name, last_name) self.worked_hours = worked_hours self.rate = rate def get_salary(self): return self.worked_hours * self.rate <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">The Payroll class<\/h2>\n\n\n\n<p>The&nbsp;<code>Payroll<\/code>&nbsp;class will have a method that adds an employee to the employee list and print out the payroll.<\/p>\n\n\n\n<p>Since fulltime and hourly employees share the same interfaces (<code>full_time<\/code>&nbsp;property and&nbsp;<code>get_salary()<\/code>&nbsp;method). Therefore, the Payroll class doesn\u2019t need to distinguish them.<\/p>\n\n\n\n<p>The following shows the\u00a0<code>Payroll<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Payroll: def __init__(self): self.employee_list = &#91;] def add(self, employee): self.employee_list.append(employee) def print(self): for e in self.employee_list: print(f\"{e.full_name} \\t ${e.get_salary()}\") <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">The main program<\/h3>\n\n\n\n<p>The following\u00a0<code>app.py<\/code>\u00a0uses the\u00a0<code>FulltimeEmployee<\/code>,\u00a0<code>HourlyEmployee<\/code>, and\u00a0<code>Payroll<\/code>\u00a0classes to print out the payroll of five employees.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from fulltimeemployee import FulltimeEmployee from hourlyemployee import HourlyEmployee from payroll import Payroll payroll = Payroll() payroll.add(FulltimeEmployee('John', 'Doe', 6000)) payroll.add(FulltimeEmployee('Jane', 'Doe', 6500)) payroll.add(HourlyEmployee('Jenifer', 'Smith', 200, 50)) payroll.add(HourlyEmployee('David', 'Wilson', 150, 100)) payroll.add(HourlyEmployee('Kevin', 'Miller', 100, 150)) payroll.print()<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>John Doe $6000 Jane Doe $6500 Jenifer Smith $10000 David Wilson $15000 Kevin Miller $15000<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">When to use abstract classes<\/h2>\n\n\n\n<p>In practice, you use abstract classes to share the code among several closely related classes. In the payroll program, all subclasses of the&nbsp;<code>Employee<\/code>&nbsp;class share the same&nbsp;<code>full_name<\/code>&nbsp;property.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about Python Abstract classes and how to use it to create a blueprint for other classes. Introduction to Python Abstract Classes In object-oriented programming, an abstract class is a\u00a0class\u00a0that cannot be instantiated. However, you can create classes that inherit from an abstract class. Typically, you use an abstract class [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[28],"tags":[],"class_list":["post-180","post","type-post","status-publish","format-standard","hentry","category-4-single-inheritance"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/180","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=180"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/180\/revisions"}],"predecessor-version":[{"id":181,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/180\/revisions\/181"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=180"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=180"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=180"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}