Start learning with our library of video tutorials taught by experts. Get started

Python 3 Essential Training
Illustration by

Using object data


From:

Python 3 Essential Training

with Bill Weinman

Video: Using object data

Object data is data that gets carried around with the object. And so when you have several objects, even several objects that are based on the same class, they can have their own set of data. Let's take a look at how this is done. And we'll make a working copy of classes.py. We'll call this, casses-working.py. I'll go ahead and open our working copy. We see that we have our Duck object and the donald instance of the object. And all of the attributes in this object are code. They are methods.
Expand all | Collapse all
  1. 5m 14s
    1. Welcome
      1m 32s
    2. Understanding prerequisites for Python
      2m 4s
    3. Using the exercise files
      1m 38s
  2. 33m 29s
    1. Getting started with "Hello World"
      4m 43s
    2. Selecting code with conditionals
      4m 45s
    3. Repeating code with a loop
      4m 13s
    4. Reusing code with a function
      2m 43s
    5. Creating sequences with generator functions
      2m 46s
    6. Reusing code and data with a class
      4m 39s
    7. Greater reusability with inheritance and polymorphism
      7m 17s
    8. Handling errors with exceptions
      2m 23s
  3. 22m 32s
    1. Installing Python 3 and Eclipse for Windows
      11m 24s
    2. Installing Python 3 and Eclipse for Mac
      11m 8s
  4. 28m 0s
    1. Creating a main script
      3m 27s
    2. Understanding whitespace in Python
      4m 8s
    3. Commenting code
      3m 28s
    4. Assigning values
      3m 37s
    5. Selecting code and values with conditionals
      4m 46s
    6. Creating and using functions
      3m 54s
    7. Creating and using objects
      4m 40s
  5. 31m 23s
    1. Understanding variables and objects in Python
      2m 46s
    2. Distinguishing mutable and immutable objects
      2m 41s
    3. Using numbers
      3m 34s
    4. Using strings
      6m 38s
    5. Aggregating values with lists and tuples
      4m 55s
    6. Creating associative lists with dictionaries
      4m 24s
    7. Finding the type and identity of a variable
      4m 45s
    8. Specifying logical values with True and False
      1m 40s
  6. 9m 42s
    1. Selecting code with if and else conditional statements
      2m 22s
    2. Setting multiple choices with elif
      2m 14s
    3. Understanding other strategies for multiple choices
      2m 38s
    4. Using the conditional expression
      2m 28s
  7. 11m 26s
    1. Creating loops with while
      1m 27s
    2. Iterating with for
      3m 54s
    3. Enumerating iterators
      3m 22s
    4. Controlling loop flow with break, continue, and else
      2m 43s
  8. 23m 28s
    1. Performing simple arithmetic
      2m 14s
    2. Operating on bitwise values
      3m 30s
    3. Comparing values
      3m 32s
    4. Operating on Boolean values
      2m 59s
    5. Operating on parts of a container with the slice operator
      6m 52s
    6. Understanding operator precedence
      4m 21s
  9. 11m 34s
    1. Using the re module
      1m 4s
    2. Searching with regular expressions
      3m 12s
    3. Replacing with regular expressions
      3m 29s
    4. Reusing regular expressions with re.compile
      3m 49s
  10. 9m 10s
    1. Learning how exceptions work
      1m 18s
    2. Handling exceptions
      4m 15s
    3. Raising exceptions
      3m 37s
  11. 23m 1s
    1. Defining functions
      6m 23s
    2. Using lists of arguments
      2m 26s
    3. Using named function arguments
      4m 32s
    4. Returning values from functions
      1m 55s
    5. Creating a sequence with a generator function
      7m 45s
  12. 47m 29s
    1. Understanding classes and objects
      5m 12s
    2. Using methods
      6m 12s
    3. Using object data
      10m 4s
    4. Understanding inheritance
      5m 11s
    5. Applying polymorphism to classes
      7m 13s
    6. Using generators
      9m 48s
    7. Using decorators
      3m 49s
  13. 18m 54s
    1. Understanding strings as objects
      3m 25s
    2. Working with common string methods
      5m 24s
    3. Formatting strings with str.format
      5m 31s
    4. Splitting and joining strings
      2m 49s
    5. Finding and using standard string methods
      1m 45s
  14. 25m 27s
    1. Creating sequences with tuples and lists
      4m 6s
    2. Operating on sequences with built-in methods
      5m 50s
    3. Organizing data with dictionaries
      4m 56s
    4. Operating on character data with bytes and byte arrays
      10m 35s
  15. 11m 46s
    1. Opening files
      2m 4s
    2. Reading and writing text files
      4m 33s
    3. Reading and writing binary files
      5m 9s
  16. 21m 27s
    1. Creating a database with SQLite 3
      6m 56s
    2. Creating, retrieving, updating, and deleting records
      7m 31s
    3. Creating a database object
      7m 0s
  17. 18m 27s
    1. Using standard library modules
      8m 0s
    2. Finding third-party modules
      5m 47s
    3. Creating a module
      4m 40s
  18. 23m 11s
    1. Dealing with syntax errors
      8m 19s
    2. Dealing with runtime errors
      4m 0s
    3. Dealing with logical errors
      4m 22s
    4. Using unit tests
      6m 30s
  19. 19m 56s
    1. Normalizing a database interface
      6m 39s
    2. Deconstructing a database application
      8m 9s
    3. Displaying random entries from a database
      5m 8s
  20. 29s
    1. Goodbye
      29s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Python 3 Essential Training
6h 36m Beginner Jul 29, 2010

Viewers: in countries Watching now:

Due to its power, simplicity, and complete object model, Python has become the scripting language of choice for many large organizations, including Google, Yahoo, and IBM. In Python 3 Essential Training, Bill Weinman demonstrates how to use Python 3 to create well-designed scripts and maintain existing projects. This course covers the basics of the language syntax and usage, as well as advanced features such as objects, generators, and exceptions. Example projects include a normalized database interface and a complete working CRUD application. Exercise files accompany the course.

Topics include:
  • A Python 3 quick start for experienced developers
  • Creating functions and objects
  • Using Python’s built-in objects and classes
  • Repeating code with loops and iterators
  • Understanding and using conditional expressions
  • Creating sequences with generators
  • Reusing code with objects and libraries
  • Handling errors with exceptions
Subjects:
Developer Web Programming Languages Web Development
Software:
Python
Author:
Bill Weinman

Using object data

Object data is data that gets carried around with the object. And so when you have several objects, even several objects that are based on the same class, they can have their own set of data. Let's take a look at how this is done. And we'll make a working copy of classes.py. We'll call this, casses-working.py. I'll go ahead and open our working copy. We see that we have our Duck object and the donald instance of the object. And all of the attributes in this object are code. They are methods.

So let's add some data to the mix. We'll do this by first creating a constructor by naming a method with two underscores and the word init and two more underscores. And we'll pass it a value, call it color and we'll give it a default value of white. It's always a good idea to give your variables default value, unless they are absolutely going to be required. And we'll save that in an object variable. Object Variable is carried with the object itself.

Remember that self is a reference to the object. So I say self._color = color. Now, I named it with an underscore for a couple of reasons. One reason is that I want to tell myself this is an attribute that I'm using locally, that I'm not going to be using directly. In other words, I'm not going to be accessing this variable from outside of the object. All of the access is going to be done from methods within the object. And for the most part, unless there's a really overriding reason to access data outside of the object without a method, then it's a really good idea to only do it with a method.

Let me show you what I mean. It I wanted to, I could assign a value to color here. I can say donald._color = 'blue'. And down here, we'll just get rid of these and we'll print donald._color. And so, I'll save this and we'll run it and we'll see that it says blue. And if I print this out twice, we'll see that the first is says white, and then it says blue.

And that's because I've gone and I've changed it here. And so this is what you call a side effect, and these can be very, very hard to keep track of. If instead, I just say I'm not going to do it that way at all. I'm going to do this all through Accessor Methods. I've a separate method for getting the color and I call this get_color and this will return self._color. And then I have another method for setting the color and I'll call this one, set_color, and I'll say self._color = color.

Now, it's all controlled and I can keep track of it much easier. And so if I want to print donald's color, I can say print donald.get_color(). Save that and we'll run it. And if I want to change his color, then I have a method that. donald.set_color(), and we'll say that their color is blue. And then we'll go ahead and print it again.

Let's go ahead and save this and run it and see what it does. You might be saying to yourself, okay so what's the difference? We just made that harder. But did we actually make it better, and the answer is, yeah we made it better. The reason that it's better is that now we have code itself has control over what happens when that gets set. Let's say when I set their color that I need to save it in a database, or that I need to do some other things. Maybe it's not just a color, maybe it's some other controlling configuration thing. Maybe ducks that have blue feathers have to also have blue feet.

So, when the color gets set, then I know that I've got a method that's going to also set the color of the feet. That's what going to also save it in the database or set some attribute some place else, based on what this change is. If I'm allowing it to get set just arbitrarily from outside of the object then I don't have that control. Then we might end up with the duck that's got blue feathers and green feet and that would never work. Bu enforcing this rule, and you'll notice when you read about object oriented code and when you learn about object oriented techniques, using these accessor methods is a standard and the reason for that is that it avoids side effects and avoids the kinds of problems that can happen when you lose control over how the data is being used.

Remember one of the major advantages of object oriented programming is the encapsulation. And once you have that encapsulation, then that gives you control, that allows you to know exactly how your data is being used. Now the other thing that we'll notice about this is that this does not scale well. If I want it to be able to set say some other flags, some other values, some other attributes, that can quickly get out of hand. If they are more than two or three of these, it would become a real problem to keep track of.

So what we tend to do in Python is to use a dictionary and to use what's called keyword arguments. If instead of just setting the color like this, I allow keyword arguments, kwargs like that and then based on those keyword arguments, I can set the color like this. That one even allows me to have a default value of white and then when I want to set it at the beginning, and let's just take these out here and I can say color equals blue, like that.

Save that and run it and we get blue. And if I don't pass the argument at all, save that and run it, then we get white. So this scales. If I wanted to say set feet = 2, I can do that. Save it and run it. Of course, I'm not setting the color, but I'm setting another attribute. And if I wanted, I can have a getter for feet. The other side of this that doesn't scale well though is that I'm saving the color in a variable like this.

Again, that could get on unwieldy and it could become difficult to keep track of. So, I can use a dictionary for that as well. In fact, I could use a dictionary for all of them and just call these variables and assign it to kwargs, like that. And for my set_color and get_color, if I wanted to have separate accessors for those, I could still do that. I could say variable sub color and assign that to the color.

And I could say variables.get('color') and give it a default value and I like to use None in a circumstance like this and I can save that. And when I run it, you'll see that we get None down here. That just tells me that donald's color has not been set. But instead of this, we can make one of these that scales as well.

Now, we're really getting into some power here. We can say set_variable and allow it the name. I'll call that k and then v for value, self.variables(), so k equals v, and get_variable(self, k). Return self.variables.get(k, None). Now instead of get_color, I can say get_variable("color").

Save that and run it. But I've set feet. I haven't set color. So I can just put feet in here and then I get the number of feet. So, this allows us scalability. This allows us, if we wanted to, even after donald has been created, we could set his color, set_variable("color") to blue, and then down here, I can get his color as well.

And now, we have this flexibility. We have a very small amount of code that can do a lot of different things. So, this is a technique that you'll see commonly used in Python where you are storing your object data in dictionary objects. It allows you a lot of flexibility. It allows you to use a lot of different data, a lot of flags, a lot of attributes, and to do different things with them, to save them to the databases, to use them as configuration options, and to vary easily be able to set them and get them and control them.

So, this is one method. Obviously, it's not the only method and we'll see a lot of examples through out the rest of this course and different ways to handle object data, but this is in a nut shell how you use object data with objects and classes in Python.

Find answers to the most frequently asked questions about Python 3 Essential Training.


Expand all | Collapse all
please wait ...
Q: The installation process for the PyDev Eclipse plug-in doesn’t work as described in the videos. What should I do?
A: The version of Eclipse used in the recording of Python 3 Essential Training was Eclipse 3.5.2 (Galileo SR2) and the version of PyDev was 1.5.7. Soon after recording, the Eclipse project was updated to version 3.6, called Helios. As of this writing, the current version of Eclipse is 3.6.1 (Helios SR1).
Around the same time as these updates were being released, the PyDev project was updated as well. As of this writing, the current version of PyDev is 1.6.2. If you are using these most recent versions, the procedure for installing Eclipse itself has not changed, but the process documented in the videos for installing PyDev may not work.

We will be releasing new versions of the videos soon, but the author has posted a document describing the new installation procedure at:
<a href="http://python.bw.org/pydev-installation/" target="blank>http://python.bw.org/pydev-installation/</a>
Q: How do you install the pydev-interpreter in Eclipse Indigo on Mac OS X Lion? It's significantly different than what's shown in the video "Installing Python 3 and Eclipse for Mac."
A: Since this course was publishing, there have been upgrades to Mac OS X and Eclipse. In this scenario, after installing Python and Eclipse and the Pydev interpreter, there is a different directory to go to when modifying the preferences. As instructed in the movie (at around 6:40) restart Eclipse and then go to Eclipse > Preferences and drill down to Pydev > Interpreter - Python in the sidebar. Click New and in the Select interpreter dialog that opens, click Browse.

The Open dialog box will open, but does not appear to display your hard drive. You must press and hold the Command+Shift+Period keys. This will display all hidden files on your system. Navigate to the new path ~/Library/Frameworks/Python.framework/versions/3.2/bin/python 3.2 and click Open.

You should be able to proceed normally from there.
Q: When I try to install PyDev, it's not showing up in the Available Software window.
A:  This can happen if the pydev.org/updates site is down.
 
    You can manually download PyDev from the pydev.org web site, or from my site here:
 
        http://python.bw.org/
 
    Installation is simple. I've included instructions on my web site above.
 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Python 3 Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.