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
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781849511261
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
€18.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
€189.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
€264.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 79.98
Mastering Object-oriented Python
€37.99
Python 3 Object Oriented Programming
€41.99
Total 79.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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.