Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Python 3 Object Oriented Programming
Python 3 Object Oriented Programming

Python 3 Object Oriented Programming: If you feel it’s time you learned object-oriented programming techniques, this is the perfect book for you. Clearly written with practical exercises, it’s the painless way to learn how to harness the power of OOP in Python.

eBook
$22.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Python 3 Object Oriented Programming

Chapter 2. Objects in Python

So, we now have a design in hand and are ready to turn that design into a working program! Of course, it doesn't usually happen that way, but this book is about programming in Python. We'll be seeing examples and hints for good software design throughout the book, but our focus is object-oriented programming. So let's have a look at the Python syntax that allows us to create object-oriented software.

After completing this chapter we will understand:

  • How to create classes and instantiate objects in Python

  • How to add attributes and behaviors to Python objects

  • How to organize classes into packages and modules

  • How to suggest people don't clobber our data

Creating Python classes


We don't have to write much Python code to realize that Python is a very "clean" language. When we want to do something, we just do it, without having to go through a lot of setup. The ubiquitous, "hello world" in Python, as you've likely seen, is only one line.

Similarly, the simplest class in Python 3 looks like this:

class MyFirstClass:
    pass

There's our first object-oriented program! The class definition starts with the class keyword. This is followed by a name (of our choice) identifying the class, and is terminated with a colon.

Note

The class name must follow standard Python variable naming rules (must start with a letter or underscore, can only be comprised of letters, underscores, or numbers). In addition, the Python style guide (search the web for "PEP 8"), recommends that classes should be named using CamelCase notation (start with a capital letter, any subsequent words should also start with a capital).

The class definition line is followed by the class contents...

Modules and packages


Now that we know how to create classes and instantiate objects, it is time to think about organizing them. For small programs, we can just put all our classes into one file and put some code at the end of the file to start them interacting. However, as our projects grow, it can become difficult to find one class that needs to be edited among the many classes we've defined. This is where modules come in. Modules are simply Python files, nothing more. The single file in our small program is a module. Two Python files are two modules. If we have two files in the same folder, we can load a class from one module for use in the other module.

For example, if we are building an e-commerce system, we will likely be storing a lot of data in a database. We can put all the classes and functions related to database access into a separate file (we'll call it something sensible: database.py). Then our other modules (for example: customer models, product information, and inventory) can...

Who can access my data?


Most object-oriented programming languages have a concept of "access control". This is related to abstraction. Some attributes and methods on an object are marked "private", meaning only that object can access them. Others are marked "protected", meaning only that class and any subclasses have access. The rest are "public", meaning any other object is allowed to access them.

Python doesn't do that. Python doesn't really believe in enforcing laws that might someday get in your way. Instead, it provides unenforced guidelines and best practices. Technically, all methods and attributes on a class are publicly available. If we want to suggest that a method should not be used publicly, we can put a note in docstrings indicating if a method is meant for internal use only, (preferably with an explanation of how the public-facing API works!).

By convention, we can also prefix an attribute or method with an underscore character: _. Most Python programmers will interpret this...

Case study


To tie it all together, let's build a simple command-line notebook application. This is a fairly simple task, so we won't be experimenting with multiple packages. We will, however, see common usage of classes, functions, methods, and docstrings.

Let's start with a quick analysis: Notes are short memos stored in a notebook. Each note should record the day it was written and can have tags added for easy querying. It should be possible to modify notes. We also need to be able to search for notes. All of this should be done from the command-line.

The obvious object is the Note. Less obvious is a Notebook container object. Tags and dates also seem to be objects, but we can use dates from Python's standard library and a comma-separated string for tags. To avoid complexity at this point, let's not define separate classes for these objects.

Note objects have attributes for the memo itself, tags, and a creation_date. Each note will also need a unique integer id, so that users can select them...

Exercises


Write some object-oriented code. The goal is to use the principles and syntax you learned in this chapter to ensure you can use it, instead of just reading about it. If you've been working on a Python project, go back over it and see if there are some objects you can create and add properties or methods to. If it's large, try dividing it into a few modules or even packages and play with the syntax.

If you don't have such a project, try starting a new one. It doesn't have to be something you intend to finish, just stub out some basic design parts. You don't need to fully implement everything, often just a print("this method will do something") is all you need to get the overall design in place. This is called top-down design, when you work out the different interactions and describe how they should work before actually implementing what they do. The converse, bottom-up design, implements details first and then ties them all together. Both patterns are useful at different times, but...

Summary


In this chapter, we learned how simple it is to create classes and assign properties and methods in Python. We also covered access control and different levels of scope (packages, modules, classes, and functions). In particular, we covered:

  • Class syntax

  • Attributes and methods

  • Initializers and constructors

  • Modules and packages

  • Relative and absolute imports

  • Access control and its limitations

In the next chapter, we'll learn how to share implementation using inheritance.

Left arrow icon Right arrow icon

Key benefits

  • Learn how to do Object Oriented Programming in Python using this step-by-step tutorial
  • Design public interfaces using abstraction, encapsulation, and information hiding
  • Turn your designs into working software by studying the Python syntax
  • Raise, handle, define, and manipulate exceptions using special error objects
  • Implement Object Oriented Programming in Python using practical examples

Description

Object Oriented Programming is a very important aspect of modern programming languages. The basic principles of Object Oriented Programming are relatively easy to learn. Putting them together into working designs can be challenging.This book makes programming more of a pleasure than a chore using powerful Python 3 object-oriented features of Python 3. It clearly demonstrates the core OOP principles and how to correctly implement OOP in Python. Object Oriented Programming ranks high in importance among the many models Python supports. Yet, many programmers never bother learning the powerful features that make this language object oriented.The book teaches when and how OOP should be correctly applied. It emphasizes not only the simple syntax of OOP in Python, but also how to combine these objects into well-designed software.This book will introduce you to the terminology of the object-oriented paradigm, focusing on object-oriented design with step-by-step examples. It will take you from simple inheritance, one of the most useful tools in the object-oriented programmer's toolbox, all the way through to cooperative inheritance, one of the most complicated. You will be able to raise, handle, define, and manipulate exceptions.You will be able to integrate the object-oriented and the not-so-object-oriented aspects of Python. You will also be able to create maintainable applications by studying higher level design patterns. You'll learn 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 will be introduced to you. You'll understand the joy of unit testing and just how easy they are to create. You'll even study higher level libraries such as database connectors and GUI toolkits and how they apply object-oriented principles.

Who is this book 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 Object Oriented Programming in Python, this is the book for you.If you are an object-oriented programmer for other languages, you too will find this book a useful introduction to Python, as it uses terminology you are already familiar with.Python 2 programmers seeking a leg up in the new world of Python 3 will also find the book beneficial, and you need not necessarily know Python 2.

What you will learn

  • Implement objects in Python by creating classes and defining methods
  • Separate different objects into a taxonomy of classes, and describe the properties and behaviors of those objects via the class interface
  • Design public interfaces using abstraction, encapsulation, and information hiding
  • Turn your designs into working software by learning the Python syntax
  • Share implementation using inheritance
  • Add functionality to the existing classes and built-ins using inheritance
  • Share similar code between classes by abstracting it into a parent class
  • Raise, handle, define, and manipulate exceptions using special error objects
  • Understand when to use object-oriented features, and more importantly when not to
  • Learn 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
  • Utilize common Python 3 modules, libraries, and frameworks

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 26, 2010
Length: 404 pages
Edition : 1st
Language : English
ISBN-13 : 9781849511278
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 26, 2010
Length: 404 pages
Edition : 1st
Language : English
ISBN-13 : 9781849511278
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 103.98
Mastering Object-oriented Python
$48.99
Python 3 Object Oriented Programming
$54.99
Total $ 103.98 Stars icon
Banner background image

Table of Contents

12 Chapters
Object-oriented Design Chevron down icon Chevron up icon
Objects in Python Chevron down icon Chevron up icon
When Objects are Alike Chevron down icon Chevron up icon
Expecting the Unexpected Chevron down icon Chevron up icon
When to Use Object-oriented Programming Chevron down icon Chevron up icon
Python Data Structures Chevron down icon Chevron up icon
Python Object-oriented Shortcuts Chevron down icon Chevron up icon
Python Design Patterns I Chevron down icon Chevron up icon
Python Design Patterns II Chevron down icon Chevron up icon
Files and Strings Chevron down icon Chevron up icon
Testing Object-oriented Programs Chevron down icon Chevron up icon
Common Python 3 Libraries Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(54 Ratings)
5 star 75.9%
4 star 18.5%
3 star 0%
2 star 1.9%
1 star 3.7%
Filter icon Filter
Top Reviews

Filter reviews by




Occ Jun 30, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am a long time software developer. I wanted to develop a skill in Python. I'm really happy that I selected this book. The case studies developed throughout the book are worth their weight in gold. They supplied the substance which helped me to learn after reading the description. This is a hands on book. Even if you have little or no object oriented experience, you will pick it up by working through the case studies and exercises. The book also provides a wealth of useful information on additional frameworks, packages, and modules which would've undoubtedly taken me a long time to figure out. Thanks for such a gret book.
Amazon Verified review Amazon
Ovata Bell Jan 30, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I ordered this book for my son. He is studying Computer Programming. He told me it is very easy to use and very helpful.
Amazon Verified review Amazon
Christopher Apr 25, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very good read for beginners to understanding the concepts of object oriented design and programming in python 3.x, only some basic experience in python syntax is necessary to get started. And the examples are very understandable. I first started learning python 10 years ago but found the OOP concepts hard to grasp but after reading this I have found going back and rewriting my old code is much more easier and efficient and I can organise it where it no longer looks like a confusing plate of spaghetti. Highly recommended for those trying to understand the basics of python OOP.
Amazon Verified review Amazon
B. Walter Finn Jan 23, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Learning a whole lot with this book. Gives a lot of practical advice on when and how to use different Python features. There are no screenshots, so I had no issues reading (or sometimes listening) on the Kindle. Starts from explaining the basics of Object Oriented concepts and gives multiple examples on how to implement. Goes into writing exceptions, using data structures appropriately, and writing basic web tools. I was actually surprised that you can build web applications without a big framework like Django. You can essentially roll your own with your knowledge of Python. Explains everything well. Good for anyone with some basic programming experience. My experience is Powershell, Bash, PHP, and a little .NET, so I felt very comfortable with the material. I had read "Python Programming for the Absolute Beginner" before tackling this one. Looking forward to implementing the concepts. This will become a good reference.
Amazon Verified review Amazon
christopher j. parrish Sep 27, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Lots of good information.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.