• 12 hours
  • Easy

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 5/23/23

Create Python Objects

Instantiate an Object

Remember the Rectangle example and its constructor? It looked a bit like this:

class Rectangle:
    def __init__(self, length, width, color=”red”):
        self.length = length
        self.width = width
        self.color = color

You use these constructors to create objects of a particular class. Now that you’ve written a few constructors, let’s use them to make an object.

Here’s an example that creates a rectangle with length 5 and width 3:

rect = Rectangle(5, 3)

When you’re instantiating an object, you usually have to assign it to a variable so you can use it. In this case, the variable name is “rect.” You could then pass  rect  around the program and call methods on it.

And the optional parameter?

If you recall, if an optional parameter wasn’t provided, the default would be used. In this case, the 5 by 3 rectangle is red.

You can specify color one of two ways:

rect1 = Rectangle(4, 2, “blue”)
rect2 = Rectangle(3, 1, color=”pink”)

The second way is more explicit and less likely to confuse when you have multiple optional parameters.

Now you have an object, so let's...

Modify an Object

Let’s say the previous rectangle is: rect = Rectangle(5, 3). Let's use it!

You can access and assign values to an object’s attributes like this:

print(rect.length)
rect.color = “yellow”

The attributes  rect.length  and  rect.color  work exactly like other variables would - they can be part of expressions or calculations, passed as parameters to functions/methods, and modified.

You can also call methods on objects using a similar syntax:

area = rect.calculate_area()
print(area)

This will print “15” for the 5 by 3 rectangle!

I thought  self  was an argument to  calculate_area()? Don’t we have to provide it?

Python deals with that for you! Remember that  self  just refers to  this object, and Python already knows what object you’re calling the method on. 

Your Turn: Make and Use Objects

In the last chapter, you wrote classes based on the toolbox example - now it’s time to use them. Copy these Screw and Nail classes into your project:

class Screw:
    MAX_TIGHTNESS = 5
    def __init__(self):
        self.tightness = 0
    def loosen(self):
        if (self.tightness > 0):
            self.tightness -= 1
    def tighten(self):
        if (self.tightness < self.MAX_TIGHTNESS):
            self.tightness += 1
    def __str__(self):
        return "Screw with tightness {}".format(self.tightness)
 
class Nail:
    def __init__(self):
        self.in_wall = False
    def nail_in(self):
        if (not self.in_wall):
            self.in_wall = True
    def remove(self):
        if (self.in_wall):
            self.in_wall = False
    def __str__(self):
        return "Nail {}in wall.".format("" if self.in_wall else "not ") 

Then, try doing the following things:

  • Instantiate a toolbox, a screwdriver, and a hammer.

  • Put the hammer and screwdriver in the toolbox.

  • Instantiate a screw, and tighten it using the screwdriver. Print the screw before and after it's been tightened.

  • Instantiate a nail, then hammer it in using the hammer. Print the nail before and after it’s been hammered in.

What else can you do with these classes and objects? After you’ve done the above tasks, see if there are any other actions you can perform.

Practice Makes Perfect: Defining a Class and Objects

Complete the following challenge to reinforce your new skills before taking the Part 1 quiz. 😁

Ready to get started? To access the exercise, click this link.

Let’s Recap!

  • You can instantiate objects using their class’s name.

  • When you instantiate an object, you’re calling its constructor, and need to provide it the right parameters.

  • You can access and modify attributes, and call methods, using the  object.attribute  syntax.

Next up is the Part 1 quiz, where you’ll recap writing classes and using objects. After that, we’ll move on to inheritance in Part 2.

Example of certificate of achievement
Example of certificate of achievement