0% found this document useful (0 votes)
2 views

Python Tutorial_ 'The ABC' of Abstract Base Classes

The document discusses abstract classes in Python, which contain abstract methods that must be implemented by subclasses. It explains that abstract classes cannot be instantiated directly and provides examples using the abc module to define abstract base classes. The document also emphasizes the importance of overriding abstract methods in subclasses and demonstrates how abstract methods can have implementations that can be enriched by subclass implementations.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Tutorial_ 'The ABC' of Abstract Base Classes

The document discusses abstract classes in Python, which contain abstract methods that must be implemented by subclasses. It explains that abstract classes cannot be instantiated directly and provides examples using the abc module to define abstract base classes. The document also emphasizes the importance of overriding abstract methods in subclasses and demonstrates how abstract methods can have implementations that can be enriched by subclass implementations.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Metaclass Use Case: Count Function Calls

Abstract Classes
Abstract classes are classes that contain one or more abstract methods. An
abstract method is a method that is declared, but contains no implementation.
Abstract classes may not be instantiated, and require subclasses to provide Follow Bernd Klein,
implementations for the abstract methods. Subclasses of an abstract class in the author of this
Python are not required to implement abstract methods of the parent class. website, at Google+:
Bernd Klein on
Let's look at the following example: Google
Python 3
class AbstractClass: Bernd Klein on
Tutorial
Facebook
def do_something(self):
The Origins of pass
Python
Search this website:
Starting with
class B(AbstractClass):
Python: The pass Go
Interactive Shell a = AbstractClass()
Executing a b = B()
Script
Indentation If we start this program, we see that this is not an abstract class, because: Python 3
Data Types and
we can instantiate an instance from This is a tutorial in
Variables we are not required to implement do_something in the class defintition of Python3, but this
Operators B chapter of our course
Sequential Data is available in a
Types: Lists and Our example implemented a case of simple inheritance which has nothing to do
version for Python
with an abstract class. In fact, Python on its own doesn't provide abstract
Strings 2.x as well: 'The ABC'
classes. Yet, Python comes with a module which provides the infrastructure for
List of Abstract Base
defining Abstract Base Classes (ABCs). This module is called - for obvious
Manipulations Classes in Python 2.x
reasons - abc.
Shallow and
Deep Copy The following Python code uses the abc module and defines an abstract base Training Classes
Dictionaries class:
Sets and Frozen This website aims at
Sets
from abc import ABC, abstractmethod providing you with
educational material
An Extensive class AbstractClassExample(ABC): suitable for self-
Example Using
learning.
Sets def __init__(self, value):
self.value = value Nevertheless, it is
input via the super().__init__() faster and more
keyboard efficient to attend a
Conditional @abstractmethod "real" Python course
Statements def do_something(self): in a classroom, with
pass an experienced
Loops, while
trainer. So why not
Loop
We will define now a subclass using the previously defined abstract class. You will notice that we haven't implemented the do_something method, even though we are required to implement it, because this method attend one of the live
For Loops is decorated as an abstract method with the decorator "abstractmethod". We get an exception that DoAdd42 can't be instantiated: Python courses
Difference
between class DoAdd42(AbstractClassExample):
interators und pass
x = DoAdd42(4)
Iterables
Output with Print The previous Python code returned the following output:
Formatted output
with string ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
modulo and the
<ipython-input-9-83fb8cead43d> in <module>()
format method 2 pass
Functions 3
Recursion and ----> 4 x = DoAdd42(4)
TypeError: Can't instantiate abstract class DoAdd42 with abstract methods do_something
Recursive
in Strasbourg, Paris,
Functions
We will do it the correct way in the following example, in which we define two classes inheriting from our abstract class: London, Berlin,
Parameter Munich, Hamburg,
Passing in Frankfurt, or Lake
Functions class DoAdd42(AbstractClassExample): Constance by Bernd
Namespaces def do_something(self): Klein, the author of
return self.value + 42 this tutorial?
Global and Local
Variables class DoMul42(AbstractClassExample):
Decorators
Memoization with def do_something(self): In-house
Decorators
return self.value * 42 Training
Read and Write
Courses
x = DoAdd42(10)
Files y = DoMul42(10)
print(x.do_something()) If you like it, we will
Modular
print(y.do_something()) come to your
Programming
company or institute
and Modules 52 and provide a special
Packages in 420 training for your
Python employees, as we've
Regular A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden. done it many times in
Expressions Amsterdam (The
You may think that abstract methods can't be implemented in the abstract base class. This impression is wrong: An abstract method can have an implementation in the abstract class! Even if they are implemented, Netherlands), Berlin
Regular
designers of subclasses will be forced to override the implementation. Like in other cases of "normal" inheritance, the abstract method can be invoked with super() call mechanism. This makes it possible to provide (Germany), Bern
Expressions,
some basic functionality in the abstract method, which can be enriched by the subclass implementation. (Switzerland), Basel
Advanced
(Switzerland), Zurich
Lambda from abc import ABC, abstractmethod (Switzerland),
Operator, Filter, Frankfurt (Germany),
Reduce and Map class AbstractClassExample(ABC):
Locarno
List @abstractmethod (Switzerland), Den
Comprehension def do_something(self): Haag (The Hague),
Iterators and print("Some implementation!") Hamburg, Munich
Generators (Germany),
class AnotherSubclass(AbstractClassExample): Bucharest (Romania),
Exception def do_something(self): Toronto (Canada),
Handling super().do_something() Edmonton (Canada),
Tests, DocTests, print("The enrichment from AnotherSubclass")
and many other
UnitTests cities. We do training
x = AnotherSubclass()
Object Oriented x.do_something() courses in England,
Programming Switzerland,
Class and Liechtenstein,
Instance Some implementation! Austria, Germany,
The enrichment from AnotherSubclass France, Belgium, the
Attributes
Netherlands,
Properties vs.
Previous Chapter: Metaclass Use Case: Count Function Calls Luxembourg,
getters and Romania, UK, Italy,
setters Spain and other
Inheritance locations in Europe
Multiple and in Canada.
Inheritance
Magic Methods This way you will get
and Operator a perfect training up
to your needs and it
Overloading
will be extremely cost
OOP, Inheritance
efficient as well.
Example
Slots Contact us so we can
Classes and find the ideal course
Class Creation to meet your needs.
Road to
Metaclasses
Metaclasses Skilled Python
Metaclass Use Programmers
Case: Count
Function Calls You are looking for
experienced Python
Abstract Classes
developers or
programmers? We
Inherently can help you, please
Abstract contact us.

"But it is a pipe." Quote of the


"No, it's not," I said. Day:
"It's a drawing of a
pipe. Get it? All
"Language designers
representations of a
want to design the
thing are inherently
perfect language.
abstract. It's very
They want to be able
clever."
to say, "My language
(John Green, The
is perfect. It can do
Fault in Our Stars)
everything." But it's
just plain impossible
to design a perfect
language, because
This website is
there are two ways to
supported by:
look at a language.
One way is by
Pyt hon Courses and looking at what can
Seminars be done with that
language. The other
is by looking at how
we feel using that
language - how we
feel while
programming." (-
Yukihiro 'Matz'
Matsumoto)

Data Protection
Declaration

Data Protection
Declaration

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like