A.8 Object-Oriented Programming in Python

Recall that we demonstrated (in Section 6.10.2) how to create a first-class counter closure in Python that encapsulates code and state and, therefore, resembles an object. Here we demonstrate how to use the object-oriented facilities in Python to develop a counter object. In both cases, we are binding an object (here, a function or method) to a specific context (or environment). In Python nomenclature, the closure approach is sometimes called nested scopes. However, in both approaches the end result is the same—a callable object (here, a function) that remembers its context.

A set of 29 code lines in Python for demonstrating how to use object-oriented facilities to develop a counter object.
Description

While the object-oriented approach is perhaps more familiar to those readers from a traditional object-oriented programming background, it executes more slowly due to the object overhead. However, the following approach permits multiple callable objects to share their signature through inheritance:

A set of six code lines in Python that permits multiple callable objects to share their signature through inheritance.
Description
Continuation of the code in Python that permits multiple callable objects to share their signature through inheritance, consisting of 25 lines.
Description

Notice that the callable object returned is bound to the environment in which it was created. In traditional object-oriented programming, an object encapsulates (or binds) multiple functions (called methods) and (to) an (the same) environment. Thus, we can augment the class new_counter with additional methods:

A set of 30 code lines in Python with the new underscore counter function.
Description
Continuation of the code in Python with the new underscore counter function consisting of seven lines.
Description
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.28.80