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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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 : 9781849511261
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Jul 26, 2010
Length: 404 pages
Edition : 1st
Language : English
ISBN-13 : 9781849511261
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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela