Extending Enumerations With New Behavior
00:00 Extending enumerations with new behavior. You can provide your enumerations with new functionality by adding new methods to your enumeration classes, as you would do with any regular Python class.
Regular methods such as
.describe_mood() are bound to instances of their containing enum, which are the enum members, so you must call regular methods on enum members rather than on the enum class itself.
.__str__() special method operates on members, providing a nicely printable representation of each member. Finally, the
.favorite_mood() method is a class method which operates on the class or enumeration itself.
01:32 can take advantage of this ability to contain additional behavior when you need to implement the strategy pattern. For example, let’s say you need a class that allows you to use two strategies for sorting a list of numbers in ascending and descending order.
Sort represents a sorting strategy. The
.__call__() special method makes the members of
Sort callable. Inside
.__call__(), you use the built-in
sorted() function to sort the input values in ascending or descending order depending on the called member.
This example is intended to demonstrate using an enum to implement the strategy design pattern. In practice, it’s unnecessary to create the
SortEnum with the sole purpose of wrapping the
03:08 Python supports multiple inheritance as part of its object-oriented features. This means that in Python you can inherit from multiple classes. When creating class hierarchies, multiple inheritance comes in handy when you want to reuse functionality from several classes at the same time. A common practice in object-oriented programming is to use what’s known as mixin classes.
In this example, the
Size class inherits from both
Enum. Inheriting from the
int type enables direct comparison between members through the greater than, less than, greater than or equal to, and less than or equal to comparison operators.
It also enables comparisons between
Size members and integer numbers. Note that when you use a data type as a mixin, the member’s
.value attribute isn’t the same as the member itself, although it’s equivalent and will compare as such.
04:49 You’ll learn more about this later on in the course. The example you’ve just seen shows that creating enumerations with mixin classes is often of great help when you need to reuse a given piece of functionality.
If you decide to use this technique in some of your enums, then you’ll have to stick to the signature seen on screen. This signature implies that you can have one or more mixin classes, at most, one data type class, and the parent
Enum class in that order.
B class, or
str, and all work as expected. However,
WrongMixinOrderEnum shows that if you put
Enum in any position other than the last, then you’ll get a
TypeError with information about the correct signature to use.
Become a Member to join the conversation.