The Purpose Enumeration
Explore how to define and apply purpose enumeration to manage classification and validation in Python objects using properties and exception handling. Understand property getters and setters to control data access and modification. This lesson highlights the use of enumerations to represent domain values and the challenges of design choices that involve conditional logic in object-oriented programming.
We'll cover the following...
Purpose enumeration
We’ll start by enumerating a domain of Purpose values:
This definition creates a namespace with three objects we can use in our code: Purpose.Classification, Purpose.Testing, and Purpose.Training. For example, we can use if sample.purpose == Purpose.Testing: to identify a testing sample.
We can convert to Purpose objects from input values using Purpose(x) where x is
an integer value, 0, 1, or 2. Any other value will raise a ValueError exception. We can convert back to numeric values, also. For example, Purpose.Training.value is 1. Using numeric codes can fit well with external software that doesn’t deal well with an enumeration of Python objects.
Implementation
Let’s decompose the KnownSample subclass of the Sample class into two parts. Here’s the first part. We initialize ...