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

Share book
  1. 466 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & 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

Book details
Book preview
Table of contents
Citations

About This Book

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.

]]>

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Python 3 Object-Oriented Programming. an online PDF/ePUB?
Yes, you can access Python 3 Object-Oriented Programming. by Dusty Phillips in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781789617078

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']}...

Table of contents