Python Object-Oriented Programming
eBook - ePub

Python Object-Oriented Programming

Build robust and maintainable object-oriented Python applications and libraries, 4th Edition

Steven F. Lott, Dusty Phillips

Compartir libro
  1. 714 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Python Object-Oriented Programming

Build robust and maintainable object-oriented Python applications and libraries, 4th Edition

Steven F. Lott, Dusty Phillips

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Python Object-Oriented Programming un PDF/ePUB en línea?
Sí, puedes acceder a Python Object-Oriented Programming de Steven F. Lott, Dusty Phillips en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2021
ISBN
9781801075237
Edición
4
Categoría
Computer Science
Categoría
Programming

9

Strings, Serialization, and File Paths

Before we get involved with higher-level design patterns, let's take a deep dive into one of Python's most common objects: the string. We'll see that there is a lot more to the string than meets the eye, and we'll also cover searching strings for patterns, and serializing data for storage or transmission.
All of these topics are elements of making objects persistent. Our application can create objects in files for use at a later time. We often take persistence – the ability to write data to a file and retrieve it at an arbitrary later date – for granted. Because persistence happens via files, at the byte level, via OS writes and reads, it leads to two transformations: data we have stored must be decoded into a nice, useful object collection of objects in memory; objects from memory need to be encoded to some kind of clunky text or bytes format for storage, transfer over the network, or remote invocation on a distant server.
In this chapter, we'll look at the following topics:
  • The complexities of strings, bytes, and byte arrays
  • The ins and outs of string formatting
  • The mysterious regular expression
  • How to use the pathlib module to manage the filesystem
  • A few ways to serialize data, including Pickle and JSON
This chapter will extend the case study to examine how best to work with collections of data files. We'll look at another serialization format, CSV, in the case study. This will help us explore alternative representations for the training and testing data.
We'll start by looking Python strings. They do so much and it's easy to overlook the wealth of available features.

Strings

Strings are a basic primitive in Python; we've used them in nearly every example we've discussed so far. All they do is represent an immutable sequence of characters. However, though you may not have considered it before, character is a bit of an ambiguous word; can Python strings represent sequences of accented characters? Chinese characters? What about Greek, Cyrillic, or Farsi?
In Python 3, the answer is yes. Python strings are all represented in Unicode, a character definition standard that can represent virtually any character in any language on the planet (and some made-up languages and random characters as well). This is done seamlessly. So, let's think of Python 3 strings as an immutable sequence of Unicode characters. We've touched on many of the ways strings can be manipulated in previous examples, but let's quickly cover it all in one place: a crash course in string theory!
It's very important to step away from the older encodings we used to know and love. The ASCII encoding, for example, was limited to one byte per character. Unicode has several ways to encode a character into bytes. The most popular, called UTF-8, tends to parallel the old ASCII encoding for some punctuation and letters. It's approximately one byte per character. But, if you need one of the thousands of other Unicode characters, there may be multiple bytes involved.
The important rule is this: we encode our characters to create bytes; we decode bytes to recover the characters. The two are separated by a high fence with a gate labeled encode on one side and decode on the other. We can visualize it like this:
Diagram

Description automatically generated
Figure 9.1: Strings and bytes
There's a potential source of confusion that arises from the canonical display of a bytes value. Python will show a bytes value as b'Flamb\xc3\xa9'. In a bytes value, the letters are shorthand for numbers and use the older ASCII encoding scheme.
For most letters, the UTF-8 and ASCII encoding are the same. The b' prefix tells us these are bytes, and the letters are really only ASCII codes, not proper Unicode characters. We can see this because the Unicode é – encoded in UTF-8 – takes two bytes, and there's no ASCII shorthand for either of those bytes.

String manipulation

As you know, strings can be created in Python by wrapping a sequence of characters in single or double quotes. Multiline strings can easily be created using three quote characters, and multiple hardcoded strings can be concatenated together by placing them side by side. Here are some examples:
>>> a = "hello" >>> b = 'world' >>> c = '''a multiple  ... line string''' >>> d = """More  ... multiple""" >>> e = ("Three " "Strings " ... "Together") 
That last string is automatically composed into a single string by the interpreter. It is also possible to concatenate strings using the + operator (as in "hello " + "world"). Of course, strings don't have to be hardcoded. They can also come from various outside sources, such as text files and user input, or can be transmitted on the network.
Watch for missing operators
The automatic concatenation of adjacent strings can make for some hilarious bugs when a comma is missed. It is, however, extremely useful when a long string needs to be placed inside a function call without exceeding the 79-character line-length limit suggested by PEP-8, the Python style guide.
Like other sequences, strings can be iterated over (character by character), indexed, sliced, or concatenated. The syntax is the same as for lists and tuples.
The ...

Índice