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.
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:
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:
3.144.28.80