We can define a type as a data structure and a set of operations that we commonly perform on that structure. This defines what is called an abstract data type (ADT). This is a formal abstraction for data types, but a class structure can be used as a beginning of practical implementations of types using the model. The underlying variables and data types used in the implementation should only be important to the person implementing the class, and all the user can do is instantiate it and use the operations.
Consider a simple type like Boolean. A Boolean variable can have one of two values, True or False. These are constants, and their actual values are not important, only that they exist and are always the same. In Python, we could have a statement
flag = True
and this gives the Boolean variable the value True. Using a class to represent a type, we could do the following:
flag = Boolean()
This is more complicated, but shows what is going on. The Boolean constructor establishes an instance of the class Boolean, which is assigned to the variable flag. We now assign a value to flag by calling its set_true method; there should also be a set_false. Now flag is a Boolean variable with the value True. We can use this in a loop by getting its value through the get method:
Boolean values can have and, or, and not operations applied to them. If we have two Boolean variables, a and b, then a and b is True only when both a is True and b is True. When implementing a Boolean class we would use a method named and to implement this operator:
result = a.and(b)
The operation or would be implemented as a method as well. The not operation is unary, meaning it operates on only one value. It reverses the truth value. We would not require a parameter for not:
A class can have variables inside them, and one special kind is a value that a class defines for programmers to use specifically with that class, usually as a constant. An example could be the values TRUE and FALSE defined as
TRUE = 1000
FALSE = 2000
These could be used outside the class as
where the name of the class is Boolean. They must, of course, not be modified after being defined inside the class. Python has not implemented constant variables, but that’s what these variables should be.
This implementation is the basis for a Boolean type. Python already has a Boolean type, but the generality of the class construct means we can create our own more complicated types.
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.