Functional Python Programming

(Wang) #1
Chapter 10

True





c3h > c2s





True





c4c != c2s





True


We didn't need to write all of the comparison method functions; they were generated
by the decorator. The decorator's creation of operators isn't perfect. In our case, we've
asked for comparisons with integers as well as between Card instances. This reveals
some problems.


Operations like the c4c > 3 and 3 < c4c commands would raise TypeError
exceptions. This is a limitation in what the total_ordering decorator can do.
The problem rarely shows up in practice, since this kind of mixed-class coercion
is relatively uncommon.


Object-oriented programming is not antithetical to functional programming. There
is a realm in which the two techniques are complementary. Python's ability to create
immutable objects works particularly well with functional programming techniques.
We can easily avoid the complexities of stateful objects, but still benefit from
encapsulation to keep related method functions together. It's particularly helpful to
define class properties that involve complex calculations; this binds the calculations
to the class definition, making the application easier to understand.


Defining number classes


In some cases, we might want to extend the numeric tower available in Python.
A subclass of numbers.Number may simplify a functional program. We can, for
example, isolate parts of a complex algorithm to the Number subclass definition,
making other parts of the application simpler or clearer.


Python already offers a rich variety of numeric types. The built-in types of the
int and float variables cover a wide variety of problem domains. When working
with currency, the decimal.Decimal package handles this elegantly. In some cases,
we might find the fractions.Fraction class to be more appropriate than the
float variable.


When working with geographic data, for example, we might consider creating
a subclass of float variable that introduces additional attributes for conversion
between degrees of latitude (or longitude) and radians. The arithmetic operations
in this subclass could be done mod()^2 π to simplify calculations that move across the
equator or the Greenwich meridian.

Free download pdf