Python 3 Object-Oriented Programming.
eBook - ePub

Python 3 Object-Oriented Programming.

Build robust and maintainable software with object-oriented design patterns in Python 3.8, 3rd Edition

Dusty Phillips

Condividi libro
  1. 466 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Python 3 Object-Oriented Programming.

Build robust and maintainable software with object-oriented design patterns in Python 3.8, 3rd Edition

Dusty Phillips

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Uncover modern Python with this guide to Python data structures, design patterns, and effective object-oriented techniques

Key Features

  • In-depth analysis of many common object-oriented design patterns that are more suitable to Python's unique style
  • Learn the latest Python syntax and libraries
  • Explore abstract design patterns and implement them in Python 3.8

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. This third edition of Python 3 Object-Oriented Programming fully explains classes, data encapsulation, and exceptions with an emphasis on when you can use each principle to develop well-designed software.Starting with a detailed analysis of object-oriented programming, you will use the Python programming language to clearly grasp key concepts from the object-oriented paradigm. You will learn how to create maintainable applications by studying higher level design patterns. The book will show you the complexities of string and file manipulation, and how Python distinguishes between binary and textual data. Not one, but two very powerful automated testing systems, unittest and pytest, will be introduced in this book. You'll get a comprehensive introduction to Python's concurrent programming ecosystem.By the end of the book, you will have thoroughly learned object-oriented principles using Python syntax and be able to create robust and reliable programs confidently.

What you will learn

  • Implement objects in Python by creating classes and defining methods
  • Grasp common concurrency techniques and pitfalls in Python 3
  • Extend class functionality using inheritance
  • Understand when to use object-oriented features, and more importantly when not to use them
  • Discover what design patterns are and why they are different in Python
  • Uncover the simplicity of unit testing and why it s so important in Python
  • Explore concurrent object-oriented programming

Who this book is for

If you're new to object-oriented programming techniques, or if you have basic Python skills and wish to learn in depth how and when to correctly apply OOP in Python, this is the book for you. If you are an object-oriented programmer for other languages or seeking a leg up in the new world of Python 3.8, you too will find this book a useful introduction to Python. Previous experience with Python 3 is not necessary.

]]>

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Python 3 Object-Oriented Programming. è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Python 3 Object-Oriented Programming. di Dusty Phillips in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781789617078
Categoria
Programming

Strings and Serialization

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 also cover searching strings for patterns, and serializing data for storage or transmission.
In particular, we'll look at the following topics:
  • The complexities of strings, bytes, and byte arrays
  • The ins and outs of string formatting
  • A few ways to serialize data
  • The mysterious regular expression

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!

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, user input, or can be encoded on the network.
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 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.
The str class has numerous methods on it to make manipulating strings easier. The dir and help commands in the Python interpreter can tell us how to use all of them; we'll consider some of the more common ones directly.
Several Boolean convenience methods help us identify whether or not the characters in a string match a certain pattern. Here is a summary of these methods. Most of these, such as isalpha, isupper/islower, and startswith/endswith, have obvious interpretations. The isspace method is also fairly obvious, but remember that all whitespace characters (including tab and newline) are considered, not just the space character.
The istitle method returns True if the first character of each word is capitalized and all other characters are lowercase. Note that it does not strictly enforce the English grammatical definition of title formatting. For example, Leigh Hunt's poem The Glove and the Lions should be a valid title, even though not all words are capitalized. Robert Service's The Cremation of Sam McGee should also be a valid title, even though there is an uppercase letter in the middle of the last word.
Be careful with the isdigit, isdecimal, and isnumeric methods, as they are more nuanced than we would expect. Many Unicode characters are considered numbers besides the 10 digits we are used to. Worse, the period character that we use to construct floats from strings is not considered a decimal character, so '45.2'.isdecimal() returns False. The real decimal character is represented by Unicode value 0660, as in 45.2 (or 45\u06602). Further, these methods do not verify whether the strings are valid numbers; 127.0.0.1 returns True for all three methods. We might think we should use that decimal character instead of a period for all numeric quantities, but passing that character into the float() or int() constructor converts that decimal character to a zero:
>>> float('45\u06602') 4502.0 
The result of all these inconsistencies is that the Boolean numeric checks are not very useful at all. We're usually much better off using a regular expression (discussed later in this chapter) to confirm whether the string matches a specific numeric pattern.
Other methods useful for pattern-matching do not return Booleans. The count method tells us how many times a given substring shows up in the string, while find, index, rfind, and rindex tell us the position of a given substring within the original string. The two r (for right or reverse) methods start searching from the end of the string. The find methods return -1 if the substring can't be found, while index raises ValueError in this situation. Have a look at some of these methods in action:
>>> s = "hello world" >>> s.count('l') 3 >>> s.find('l') 2 >>> s.rindex('m') Traceback (most recent call last):  File "<stdin>", line 1, in <module> ValueError: substring not found 
Most of the remaining string methods return transformations of the string. The upper, lower, capitalize, and title methods create new strings with all alphabetical characters in the given format. The translate method can use a dictionary to map arbitrary input characters to specified output characters.
For all of these methods, note that the input string remains unmodified; a brand new str instance is returned instead. If we need to manipulate the resultant string, we should assign it to a new variable, as in new_value=value.capitalize(). Often, once we've performed the transformation, we don't need the old value anymore, so a common idiom is to assign it to the same variable, as in value=value.title().
Finally, a couple of string methods return or operate on lists. The split method accepts a substring and splits the string into a list of strings wherever that substring occurs. You can pass a number as a second parameter to limit the number of resultant strings. The rsplitmethod behaves identically to split if you don't limit the number of strings, but if you do supply a limit, it starts splitting from the end of the string. The partition and rpartition methods split the string at only the first or last occurrence of the substring, and return a tuple of three values: characters before the substring, the substring itself, and the characters after the substring.
As the inverse of split, the join method accepts a list of strings, and returns all of those strings combined together by placing the original string between them. The replace method accepts two arguments, and returns a string where each instance of the first argument has been replaced with the second. Here are some of these methods in action:
>>> s = "hello world, how are you" >>> s2 = s.split(' ') >>> s2 ['hello', 'world,', 'how', 'are', 'you'] >>> '#'.join(s2) 'hello#world,#how#are#you' >>> s.replace(' ', '**') 'hello**world,**how**are**you' >>> s.partition(' ') ('hello', ' ', 'world, how are you') 
There you have it, a whirlwind tour of the most common methods on the str class! Now, let's look at Python 3's method for composing strings and variables to create new strings.

String formatting

Python 3 has powerful string formatting and templating mechanisms that allow us to construct strings comprised of hardcoded text and interspersed variables. We've used it in many previous examples, but it is much more versatile than the simple formatting specifiers we've used.
A string can be turned into a format string (also called an f-string) by prefixing the opening quotation mark with an f, as in f"hello world". If such a string contains the special characters { and }, variables from the surrounding scope can be used to replace them as in this example:
name = "Dusty"
activity = "writing"
formatted = f"Hello {name}, you are currently {activity}."
print(formatted)
If we run these statements, it replaces the braces with variables, in order:
Hello Dusty, you are currently writing. 

Escaping braces

Brace characters are often useful in strings, aside from formatting. We need a way to escape them in situations where we want them to be displayed as themselves, rather than being replaced. This can be done by doubling the braces. For example, we can use Python to format a basic Java program:
classname = "MyClass"
python_code = "print('hello world')"
template = f"""
public class {classname} {{
public static void main(String[] args) {{
System.out.println("{python_code}");
}}
}}"""

print(template)
Where we see the {{ or }} sequence in the templatethat is, the braces enclosing the Java class and method definitionwe know the f-string will replace them with single braces, rather than some argument in the surrounding methods. Here's the output:
public class MyClass {  public static void main(String[] args) {  System.out.println("print('hello world')");  } } 
The class name and contents of the output have been replaced with two parameters, while the double braces have been replaced with single braces, giving us a valid Java file. Turns out, this is about the simplest possible Python program to print the simplest possible Java program that can print the simplest possible Python program.

f-strings can contain Python code

We aren't restricted to passing simple string variables into an f-string method. Any primitives, such as integers or floats, can be formatted. More interestingly, complex objects, including lists, tuples, dictionaries, and arbitrary objects can be used, and we can access indexes and variables or call functions on those objects from within the format string.
For example, if our email message had grouped the From and To email addresses into a tuple, and placed the subject and message in a dictionary, for some reason (perhaps because that's the input required for an existing send_mail function we want to use), we can format it like this:
emails = ("[email protected]", "[email protected]")
message = {
"subject": "You Have Mail!",
"message": "Here's some mail for you!",
}

formatted = f"""
From: <{emails[0]}>
To: <{emails[1]}>
Subject: {message['subject']}
{message['message']}"""
print(formatted)
The variables inside the braces in the template string look a little weird, so let's look at what they're doing. The two email addresses are looked up by emails[x], where x is either 0 or 1. The square brackets with a number inside are the same kind of index lookup we see in regular Python code, so emails[0] refers to the first item in the emails tuple. The indexing syntax works with any indexable object, so we see similar behavior when we access message[subject], except this time we are looking up a string key in a dictionary. Notice that, unlike in Python code, we do not need to put quotes around the string in the dictionary lookup.
We can even do multiple levels of lookup if we have nested data structures. If we modify the above code to put the emails tuple inside the message dictionary, we can use an indexed lookup as follows:
message["emails"] = emails

formatted = f"""
From: <{message['emails'][0]}>
To: <{message['emails'][1]}>
Subject: {message['subject']}
{message['message']}...

Indice dei contenuti