Python Object-Oriented Programming - Fourth Edition

Book description

A comprehensive guide to exploring modern Python through data structures, design patterns, and effective object-oriented techniques

Key Features

  • Build an intuitive understanding of object-oriented design, from introductory to mature programs
  • Learn the ins and outs of Python syntax, libraries, and best practices
  • Examine a machine-learning case study at the end of each chapter

Book Description

Object-oriented programming (OOP) is a popular design paradigm in which data and behaviors are encapsulated in such a way that they can be manipulated together. Python Object-Oriented Programming, Fourth Edition dives deep into the various aspects of OOP, Python as an OOP language, common and advanced design patterns, and hands-on data manipulation and testing of more complex OOP systems. These concepts are consolidated by open-ended exercises, as well as a real-world case study at the end of every chapter, newly written for this edition. All example code is now compatible with Python 3.9+ syntax and has been updated with type hints for ease of learning.

Steven and Dusty provide a comprehensive, illustrative tour of important OOP concepts, such as inheritance, composition, and polymorphism, and explain how they work together with Python's classes and data structures to facilitate good design. In addition, the book also features an in-depth look at Python's exception handling and how functional programming intersects with OOP. Two very powerful automated testing systems, unittest and pytest, are introduced. The final chapter provides a detailed discussion of Python's concurrent programming ecosystem.

By the end of the book, you will have a thorough understanding of how to think about and apply object-oriented principles using Python syntax and be able to confidently create robust and reliable programs.

What you will learn

  • Implement objects in Python by creating classes and defining methods
  • Extend class functionality using inheritance
  • Use exceptions to handle unusual situations cleanly
  • Understand when to use object-oriented features, and more importantly, when not to use them
  • Discover several widely used design patterns and how they are implemented in Python
  • Uncover the simplicity of unit and integration testing and understand why they are so important
  • Learn to statically type check your dynamic code
  • Understand concurrency with asyncio and how it speeds up programs

Who this book is for

If you are new to object-oriented programming techniques, or if you have basic Python skills and wish to learn how and when to correctly apply OOP principles in Python, this is the book for you. Moreover, if you are an object-oriented programmer coming from other languages or seeking a leg up in the new world of Python, you will find this book a useful introduction to Python. Minimal previous experience with Python is necessary.

Table of contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. Object-Oriented Design
    1. Introducing object-oriented
    2. Objects and classes
    3. Specifying attributes and behaviors
      1. Data describes object state
      2. Behaviors are actions
    4. Hiding details and creating the public interface
    5. Composition
    6. Inheritance
      1. Inheritance provides abstraction
      2. Multiple inheritance
    7. Case study
      1. Introduction and problem overview
      2. Context view
      3. Logical view
      4. Process view
      5. Development view
      6. Physical view
      7. Conclusion
    8. Recall
    9. Exercises
    10. Summary
  3. Objects in Python
    1. Introducing type hints
      1. Type checking
    2. Creating Python classes
      1. Adding attributes
      2. Making it do something
        1. Talking to yourself
        2. More arguments
      3. Initializing the object
      4. Type hints and defaults
      5. Explaining yourself with docstrings
    3. Modules and packages
      1. Organizing modules
        1. Absolute imports
        2. Relative imports
        3. Packages as a whole
      2. Organizing our code in modules
    4. Who can access my data?
    5. Third-party libraries
    6. Case study
      1. Logical view
      2. Samples and their states
      3. Sample state transitions
      4. Class responsibilities
      5. The TrainingData class
    7. Recall
    8. Exercises
    9. Summary
  4. When Objects Are Alike
    1. Basic inheritance
      1. Extending built-ins
      2. Overriding and super
    2. Multiple inheritance
      1. The diamond problem
      2. Different sets of arguments
    3. Polymorphism
    4. Case study
      1. Logical view
      2. Another distance
    5. Recall
    6. Exercises
    7. Summary
  5. Expecting the Unexpected
    1. Raising exceptions
      1. Raising an exception
      2. The effects of an exception
      3. Handling exceptions
      4. The exception hierarchy
      5. Defining our own exceptions
      6. Exceptions aren't exceptional
    2. Case study
      1. Context view
      2. Processing view
      3. What can go wrong?
      4. Bad behavior
      5. Creating samples from CSV files
      6. Validating enumerated values
      7. Reading CSV files
      8. Don't repeat yourself
    3. Recall
    4. Exercises
    5. Summary
  6. When to Use Object-Oriented Programming
    1. Treat objects as objects
    2. Adding behaviors to class data with properties
      1. Properties in detail
      2. Decorators – another way to create properties
      3. Deciding when to use properties
    3. Manager objects
      1. Removing duplicate code
      2. In practice
    4. Case study
      1. Input validation
      2. Input partitioning
      3. The sample class hierarchy
      4. The purpose enumeration
      5. Property setters
      6. Repeated if statements
    5. Recall
    6. Exercises
    7. Summary
  7. Abstract Base Classes and Operator Overloading
    1. Creating an abstract base class
      1. The ABCs of collections
      2. Abstract base classes and type hints
      3. The collections.abc module
      4. Creating your own abstract base class
      5. Demystifying the magic
    2. Operator overloading
    3. Extending built-ins
    4. Metaclasses
    5. Case study
      1. Extending the list class with two sublists
      2. A shuffling strategy for partitioning
      3. An incremental strategy for partitioning
    6. Recall
    7. Exercises
    8. Summary
  8. Python Data Structures
    1. Empty objects
    2. Tuples and named tuples
      1. Named tuples via typing.NamedTuple
    3. Dataclasses
    4. Dictionaries
      1. Dictionary use cases
      2. Using defaultdict
        1. Counter
    5. Lists
      1. Sorting lists
    6. Sets
    7. Three types of queues
    8. Case study
      1. Logical model
      2. Frozen dataclasses
      3. NamedTuple classes
      4. Conclusion
    9. Recall
    10. Exercises
    11. Summary
  9. The Intersection of Object-Oriented and Functional Programming
    1. Python built-in functions
      1. The len() function
      2. The reversed() function
      3. The enumerate() function
    2. An alternative to method overloading
      1. Default values for parameters
        1. Additional details on defaults
      2. Variable argument lists
      3. Unpacking arguments
    3. Functions are objects, too
      1. Function objects and callbacks
      2. Using functions to patch a class
      3. Callable objects
    4. File I/O
      1. Placing it in context
    5. Case study
      1. Processing overview
      2. Splitting the data
      3. Rethinking classification
      4. The partition() function
      5. One-pass partitioning
    6. Recall
    7. Exercises
    8. Summary
  10. Strings, Serialization, and File Paths
    1. Strings
      1. String manipulation
      2. String formatting
        1. Escaping braces
        2. f-strings can contain Python code
        3. Making it look right
        4. Custom formatters
        5. The format() method
      3. Strings are Unicode
        1. Decoding bytes to text
        2. Encoding text to bytes
        3. Mutable byte strings
    2. Regular expressions
      1. Matching patterns
        1. Matching a selection of characters
        2. Escaping characters
        3. Repeating patterns of characters
        4. Grouping patterns together
      2. Parsing information with regular expressions
        1. Other features of the re module
        2. Making regular expressions efficient
    3. Filesystem paths
    4. Serializing objects
      1. Customizing pickles
      2. Serializing objects using JSON
    5. Case study
      1. CSV format designs
      2. CSV dictionary reader
      3. CSV list reader
      4. JSON serialization
      5. Newline-delimited JSON
      6. JSON validation
    6. Recall
    7. Exercises
    8. Summary
  11. The Iterator Pattern
    1. Design patterns in brief
    2. Iterators
      1. The iterator protocol
    3. Comprehensions
      1. List comprehensions
      2. Set and dictionary comprehensions
      3. Generator expressions
    4. Generator functions
      1. Yield items from another iterable
      2. Generator stacks
    5. Case study
      1. The Set Builder background
      2. Multiple partitions
      3. Testing
      4. The essential k-NN algorithm
      5. k-NN using the bisect module
      6. k-NN using the heapq module
      7. Conclusion
    6. Recall
    7. Exercises
    8. Summary
  12. Common Design Patterns
    1. The Decorator pattern
      1. A Decorator example
      2. Decorators in Python
    2. The Observer pattern
      1. An Observer example
    3. The Strategy pattern
      1. A Strategy example
      2. Strategy in Python
    4. The Command pattern
      1. A Command example
    5. The State pattern
      1. A State example
      2. State versus Strategy
    6. The Singleton pattern
      1. Singleton implementation
    7. Case study
    8. Recall
    9. Exercises
    10. Summary
  13. Advanced Design Patterns
    1. The Adapter pattern
      1. An Adapter example
    2. The Façade pattern
      1. A Façade example
    3. The Flyweight pattern
      1. A Flyweight example in Python
      2. Multiple messages in a buffer
      3. Memory optimization via Python's __slots__
    4. The Abstract Factory pattern
      1. An Abstract Factory example
      2. Abstract Factories in Python
    5. The Composite pattern
      1. A Composite example
    6. The Template pattern
      1. A Template example
    7. Case study
    8. Recall
    9. Exercises
    10. Summary
  14. Testing Object-Oriented Programs
    1. Why test?
      1. Test-driven development
      2. Testing objectives
      3. Testing patterns
    2. Unit testing with unittest
    3. Unit testing with pytest
      1. pytest's setup and teardown functions
      2. pytest fixtures for setup and teardown
      3. More sophisticated fixtures
      4. Skipping tests with pytest
    4. Imitating objects using Mocks
      1. Additional patching techniques
      2. The sentinel object
    5. How much testing is enough?
    6. Testing and development
    7. Case study
      1. Unit testing the distance classes
      2. Unit testing the Hyperparameter class
    8. Recall
    9. Exercises
    10. Summary
  15. Concurrency
    1. Background on concurrent processing
    2. Threads
      1. The many problems with threads
        1. Shared memory
        2. The global interpreter lock
        3. Thread overhead
    3. Multiprocessing
      1. Multiprocessing pools
      2. Queues
      3. The problems with multiprocessing
    4. Futures
    5. AsyncIO
      1. AsyncIO in action
      2. Reading an AsyncIO future
      3. AsyncIO for networking
        1. Design considerations
      4. A log writing demonstration
      5. AsyncIO clients
    6. The dining philosophers benchmark
    7. Case study
    8. Recall
    9. Exercises
    10. Summary
  16. Other Books You May Enjoy
  17. Index

Product information

  • Title: Python Object-Oriented Programming - Fourth Edition
  • Author(s): Steven F. Lott, Dusty Phillips
  • Release date: July 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781801077262