In this chapter, we discussed the details of crafting valuable classes. You saw how to define a class, create objects of the class, access an object’s attributes and call its methods. You define the special method __init__
to create and initialize a new object’s data attributes.
We discussed controlling access to attributes and using properties. We showed that all object attributes may be accessed directly by a client. We discussed identifiers with single leading underscores (_
), which indicate attributes that are not meant to be accessed by client code. We showed how to implement “private” attributes via the double-leading-underscore (__
) naming convention, which tells Python to mangle an attribute’s name.
We implemented a card shuffling and dealing simulation consisting of a Card
class and a DeckOfCards
class that maintained a list of Card
s, and displayed the deck both as strings and as card images using Matplotlib. We introduced special methods __repr__
, __str__
and __format__
for creating string representations of objects.
Next, we looked at Python’s capabilities for creating base classes and subclasses. We showed how to create a subclass that inherits many of its capabilities from its superclass, then adds more capabilities, possibly by overriding the base class’s methods. We created a list containing both base class and subclass objects to demonstrate Python’s polymorphic programming capabilities.
We introduced operator overloading for defining how Python’s built-in operators work with objects of custom class types. You saw that overloaded operator methods are implemented by overriding various special methods that all classes inherit from class object
. We discussed the Python exception class hierarchy and creating custom exception classes.
We showed how to create a named tuple that enables you to access tuple elements via attribute names rather than index numbers. Next, we introduced Python 3.7’s new data classes, which can autogenerate various boilerplate code commonly provided in class definitions, such as the __init__
, __repr__
and __eq__
special methods.
You saw how to write unit tests for your code in docstrings, then execute those tests conveniently via the doctest
module’s testmod
function. Finally, we discussed the various namespaces that Python uses to determine the scopes of identifiers. In the next chapter, we’ll introduce the computer science concepts of recursion, searching and sorting and Big O.
3.145.166.7