Hour 10. Making Objects


What You’ll Learn in This Hour:

Image What object-oriented programming is

Image How to plan your objects

Image How to make objects out of objects

Image When to use objects in the real world


An object in Python is anything that has values and functions attached to it. You can make your own, import them from other libraries, or use the ones we’ve already been playing with.

Object-Oriented Programming

Object-oriented programming (OOP) is a way of bundling code so that functions and variables can be all in one place. It can seem confusing at first, but really, objects in programming are much like the objects around us.

Earlier, we compared variables to cups. A cup is an even better analogy for an object. As we discussed, cups can hold food or liquid, which we compared to the data we can store in variables. But cups also have a number of functions. You can use their handle to pick them up. You can touch their side to tell if whatever is in them is hot or cold. You can even look inside to see if there’s anything actually in the cup.

If a cup was translated into code, we might say its values are whatever is inside it, and its functions are testing for temperature, moving the cup, and seeing if it has anything in it.

In a way, objects better resemble the real world than variables do. After all, almost everything we touch and see has more than one aspect to it. Look at Figure 10.1. Are you just your name or an ID number? No! You have a birth date, you have a home. Your hair is a certain color. You like some things more than other things. You can perform actions, such as reading, programming, and eating. You have friends and family.

Image

FIGURE 10.1 You, and everything about you.

Again, an object in Python is anything that has values and functions attached to it. You can make your own, import them from other libraries, or use the ones that we’ve already been playing with.

In Python, every variable is an object. All of the data types we’ve been working with have functions attached to them, but normally only one value. For example, a string holds a set of characters, whereas an int holds a number. Even a list only holds one list of items.

Objects We’re Already Using

Ints, floats, longs, strings, dictionaries, and lists are all objects in Python. You’ve already been using some of their extra functions. For example, getting the title case for a string is an extra function, as is getting all the keys out of a dictionary. Here are a few of the functions you can use with the data types you’ve already learned:

>>> mydict.keys()
['peaches', 'papaya', 'apples']
>>> mynum.hex()
'0x1.91eb851eb851fp+1'
>>> mylist.append(999)
>>> mylist
[0, 1, 1, 2, 3, 5, 8, 999
>>> mystring.title()
'Hello, World']

As you can see, sometimes the functions get information about the data stored in the object. Sometimes, though, the functions change the contents of the object. For example, keys() is used to get all the keys in a dictionary, whereas append() is used to add a new item to the end of a list. Other functions change the way the data is formatted, such as how title() is used to put a string into title case.

Objects

Some might wonder why we should bother to group our data into objects. Why not just make a pile of variables and pass them around to functions? Why not store our data in lists of lists where we keep track of what kind of data we’re keeping in each index? It can be tempting to just use the data structures you already know, rather than go through the effort of making your own.

As your programs grow more complex, keeping track of data gets more and more difficult. Let’s run through an instance where you may eventually decide to go with a custom data type: keeping track of users.

When you first decide to keep track of users for your application, you may only store their usernames. For this, a list of strings will do:

users = ['ojohnson', 'dhellmann', 'mblum']

Later, though, someone may ask you to start storing their first and last names, along with an email address. Maybe a list of lists would be better? You’ll just have to remember that you put the username in the first index, the first name in the second index, and the last name in the third index, as follows:

users = [['ojohnson', 'Olwen', 'Johnson'],
    ['dhellman', 'Doug', 'Hellmann'],
    ['mblum', 'Manny', 'Blum']]

Say you get a new request: You now need to keep track of when the user joined, and when he or she last logged in. Keeping track of all of that, just using lists or dictionaries, can become daunting quickly.

Also, imagine trying to hand over your program to others to maintain. It would be nearly impossible for them to quickly figure out what data you were storing and how. They would also have to be careful about editing the way you’ve stored your data, just in case the order was vital for certain functions.

Also, every time you make one of the preceding changes, you have to go back and change how your program works. With the first example, users are stored as strings, so users[0] would give you the first user. That doesn’t work for the second example, though. users[0] would return a list. To get a username, you need to use users[0][0].

What if we had some sort of variable that held all the information we would need about a user? Wouldn’t it be nicer if we could do something like the following:

>>> print me
Username: kcunning
Katie Cunningham
Joined: 5/14/2013
Last seen: 5/14/2013
>>> me.get_date_string(me.joined)
'5/14/2013'
>>> me.first_name
'Katie'
>>> me.last_name
'Cunningham'
>>> me.username
'kcunning'

We could add more values to the user object without worrying about what order we put things in. We could customize the format for when someone decides to print the user. We could even add functions to do things such as update some of the values and give the time since the user joined.

Vocabulary

Before we move on, we should discuss some terms you’ll need to know in order to work with objects. Knowing the correct terms helps when trying to talk with others about your code, or when trying to search for the solution to a problem you’re having.

Image Attributes— These are the values an object has. In the user example, one attribute is 'first_name', and 'last_name' is another attribute.

Image Methods— These are the functions attached to your object. They can only be used with their object. In the user example, get_date_string() is a method.

Image Instance— Whenever you make a new object, it’s called an “instance.” This is just like creating a new string. Technically, when you create a new variable and set it to a value, you’re creating an instance of that data type.

Changing a value in one instance only changes it for that instance, not for all objects of that data type. So, if we had two users and change the first name for one of them, that would only change the first name for that instance of the user data type.

Image Class— The blueprint for an object. A class defines the methods and attributes for your object, as well as sets any default values.

Image Subclass— When you base a new class off an existing class, you are subclassing it. It gains all the attributes, default values, and functions of the parent class.

Planning an Object

Ideally, you would want to make a new object when you have at least one attribute that you know you’ll want to perform a certain amount of methods on. For example, a year might not be something that you’d want to make a custom object for, but a recipe is.

Objects take some planning. There are many tools to help you plan out what you need an object to do, but what works great is paper and pencil. Whenever you need to plan a new object for a program, ask yourself a few questions:

Image What attributes do I want this object to have?

Image How am I going to change these attributes?

Image Do I need to print out this object, or parts of this object, in a special way?

Let’s say you want to plan out an object for a recipe. Figure 10.2 shows a rough plan, including some attributes and a few methods.

Image

FIGURE 10.2 Planning objects for a recipe.

You’ve already planned out what sort of data types your attributes should be, as well how you’re going to update them, and you set aside a method just for printing the recipe. Why would you have methods to update the values in your object? In general, it’s better to set aside an indirect way of changing the attributes in an object. You can do some data checking on the incoming values. What if someone decided to save a dictionary in the directions variable? This could wreak havoc with the program.

This isn’t always necessary, though. Some people prefer cleaner code to one filled with functions for displaying and changing variables. In this case, you have all the functions spelled out because you plan on having some user-friendly inputs to help the user along.

Making Objects Out of Objects

Making your code more organized is only one benefit of using objects. Another more powerful benefit is something called inheritance. You can define an object by pointing to an existing object and then adding on more attributes and methods. This way, you don’t have to keep rewriting code to do the same things, but for slightly different items.

For example, let’s say you want to build an application for a bookstore. Bookstores sell more than books. Most sell magazines as well. Some sell CDs. Some stores even sell software, such as language learning suites.

What do all of these items have in common? They all have a price (unless this is a rather generous bookstore), they should all have a title of some sort, and we can probably give each of them a description. Let’s plan out a base object, from which all the other objects will inherit. These are listed in Figure 10.3.

Image

FIGURE 10.3 Bookstore item attributes.

Now that we have some of our attributes settled, what about methods? We don’t know what we’ll be doing with these objects yet, so for right now, let’s just set aside some methods for updating the attributes we have already (see Figure 10.4).

Image

FIGURE 10.4 Bookstore item methods.

For now, this is as far as we feel we can go with a generic object. Let’s make some objects that inherit from it. Because our store will sell magazines, software, and books, we can make an object for each of these that has attributes and functions that are specific to each one. In Figure 10.5, all the objects we’re going to build have been laid out.

Image

FIGURE 10.5 Plan for all bookstore items.

Book, Magazine, and Software will all inherit the attributes of the base bookstore item, so there’s no need to redefine them. For example, the Book object will have a title, description, and price (defined by our first object), as well as an author and a format (defined by the Book object). This saves us quite a bit of time when it comes to coding, and it can also save us time down the road.

Let’s say the owner of the bookstore looks over your plan for your objects and points out that you missed something: the inventory ID. Everything in the shop has an ID number associated with a unique ID that allows them to perform an inventory more easily. Rather than edit Book, Magazine, and Software, you can simply edit the base class (see Figure 10.6).

Image

FIGURE 10.6 Adding ID to all bookstore objects.

Now, by adding one attribute to one object, we have updated Book, Magazine, and Software!

Using Objects in the Real World

How could the restaurant from earlier examples benefit from using objects? How about automating the menu? Many restaurants have both a printed menu and a menu online, as well as a menu that they hand out to people wanting carry-out or delivery. This means when an item has to be added or removed, all three menus have to be updated.

The manager is tired of forgetting to update one of the menus and dealing with customers who are unhappy that the meal they were planning on is no longer offered. He decides to set about planning a program that will eventually be used to print out the menus in several formats, but all menus will be saved in one place. That way, he and the cook can edit once and change all of the menus at once. He may not know how to do all the programming yet, but he hopes that in planning a bit, he can figure out the right questions to ask.

First, he creates his menu item (see Figure 10.7). A menu item should have a title, a cost, some descriptions, and should probably be set to a meal type (for example, appetizer, side, or special). He also writes down some methods he thinks he’ll need in order to change these attributes.

Image

FIGURE 10.7 Menu item plan.

Next, he sets about planning his actual menu. He realizes that a menu is just a list of items. He could just make a list of lists, or use a dictionary, but he realizes he may want to expand his menu object later on. Besides, if he used a dictionary, he couldn’t add on special methods for printing out his different menus (see Figure 10.8).

Image

FIGURE 10.8 Menu plan.

Now, with his plan in hand, he can start thinking about his future program.

Summary

During this hour, you learned that your code can be organized into items called objects. Objects contain both values and functions within them. You learned about planning an object as well as extending objects to create new objects.

Q&A

Q. I just searched the Internet for “object-oriented programming” and there’s a ton of information out there! Can I really learn to use objects?

A. It’ll be okay! Object-oriented programming has been around for a long time, so there’s lots of literature about it. The phrase was first coined in the 1950s at MIT. That’s quite a bit of time for opinions and theories to build up. OOP can be intimidating at first, but remember, at its core, you’re bundling data and functions together. As time goes on, you’ll get better and better at organizing your data.

Q. Is object-oriented programming the only way to organize my programs?

A. Not at all! There’s dozens of ways to organize your programs. Some languages work better with some methods, and some can work with multiple methods. These are called programming models. Hour 24, “Taking the Next Steps with Python,” goes over some of the other models popular right now that will work with Python.

Workshop

The Workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the answers that follow.

Quiz

1. What is the difference between an object’s attributes and its methods?

2. What is an instance?

3. Why should you learn how to use objects?

Answers

1. An attribute stores a value, whereas a method works like a function.

2. When you create a new object, it’s considered an instance of that object’s data type. It is completely independent of all other instances of that data type.

3. Objects can help make your code easier to manage by bundling together values and functions.

Exercise

You’ve been asked to plan out the objects for a pet store. Think of the things a pet store might have, what functions you might want to attach to them, and what attributes they might have. Don’t forget to use inheritance to make your life a bit easier.

Here are some examples of things that might be in the store (to get you started):

Image Different kinds of animals

Image Pet food

Image Toys

Image Books on pet care

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.101.109