Online Book Reader

Home Category

Learning Python - Mark Lutz [421]

By Root 1445 0
class changes and extensions, static and class methods, function decorators, and more.

As we’ve seen, Python’s OOP model is, at its core, very simple, and some of the topics presented in this chapter are so advanced and optional that you may not encounter them very often in your Python applications-programming career. In the interest of completeness, though, we’ll round out our discussion of classes with a brief look at these advanced tools for OOP work.

As usual, because this is the last chapter in this part of the book, it ends with a section on class-related “gotchas,” and the set of lab exercises for this part. I encourage you to work through the exercises to help cement the ideas we’ve studied here. I also suggest working on or studying larger OOP Python projects as a supplement to this book. As with much in computing, the benefits of OOP tend to become more apparent with practice.

* * *

Note


Content note: This chapter collects advanced class topics, but some are even too advanced for this chapter to cover well. Topics such as properties, descriptors, decorators, and metaclasses are only briefly mentioned here, and are covered more fully in the final part of this book. Be sure to look ahead for more complete examples and extended coverage of some of the subjects that fall into this chapter’s category.

* * *

Extending Built-in Types

Besides implementing new kinds of objects, classes are sometimes used to extend the functionality of Python’s built-in types to support more exotic data structures. For instance, to add queue insert and delete methods to lists, you can code classes that wrap (embed) a list object and export insert and delete methods that process the list specially, like the delegation technique we studied in Chapter 30. As of Python 2.2, you can also use inheritance to specialize built-in types. The next two sections show both techniques in action.

Extending Types by Embedding

Remember those set functions we wrote in Chapters 16 and 18? Here’s what they look like brought back to life as a Python class. The following example (the file setwrapper.py) implements a new set object type by moving some of the set functions to methods and adding some basic operator overloading. For the most part, this class just wraps a Python list with extra set operations. But because it’s a class, it also supports multiple instances and customization by inheritance in subclasses. Unlike our earlier functions, using classes here allows us to make multiple self-contained set objects with preset data and behavior, rather than passing lists into functions manually:

class Set:

def __init__(self, value = []): # Constructor

self.data = [] # Manages a list

self.concat(value)

def intersect(self, other): # other is any sequence

res = [] # self is the subject

for x in self.data:

if x in other: # Pick common items

res.append(x)

return Set(res) # Return a new Set

def union(self, other): # other is any sequence

res = self.data[:] # Copy of my list

for x in other: # Add items in other

if not x in res:

res.append(x)

return Set(res)

def concat(self, value): # value: list, Set...

for x in value: # Removes duplicates

if not x in self.data:

self.data.append(x)

def __len__(self): return len(self.data) # len(self)

def __getitem__(self, key): return self.data[key] # self[i]

def __and__(self, other): return self.intersect(other) # self & other

def __or__(self, other): return self.union(other) # self | other

def __repr__(self): return 'Set:' + repr(self.data) # print()

To use this class, we make instances, call methods, and run defined operators as usual:

x = Set([1, 3, 5, 7])

print(x.union(Set([1, 4, 7]))) # prints Set:[1, 3, 5, 7, 4]

print(x | Set([1, 4, 6])) # prints Set:[1, 3, 5, 7, 4, 6]

Overloading operations such as indexing enables instances of our Set class to masquerade as real lists. Because you will interact with and extend this class in an exercise at the end of this chapter, I won’t say much more about this code until Appendix B.

Extending Types by Subclassing

Return Main Page Previous Page Next Page

®Online Book Reader