From the course: Python: Advanced Design Patterns

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Template method example

Template method example

- [Instructor] Python 3 has a built-in feature that allows us to designate a certain method as an abstract method. When a method is decorated as an abstract method, it should be overridden by a subclass. To use this handy Python feature, let's import abstract based classes or in short, ABC. So let's type from abc, import ABC, abstractmethod. Next, let's define our classes. The first one to work on is our abstract class where we define a template method as you saw in the UML class diagram for the template method pattern. So the AbstractClass is this one. In the template_method, we'll call four methods as part of an algorithm, a couple of operations of which will be defined by concrete classes. So the template_method is defined here. The first method is a protected method that should never be overridden. It is always called by default. So simply type self.__always_do_this(). Note that we are using two underscores for the method name. This is a Python's way of designating this method…

Contents