Skip to the content

Methods

Python · Unit 12: Classes and objects

A method is a function that lives inside the class. Like __init__, it first receives self, so it can use the object's data.

You call it with a dot: luna.greet(). You already know a few: items.append(5) and text.upper() are methods.

class Pet:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print("I'm", self.name)

luna = Pet("Luna")
luna.greet()

Prints

I'm Luna

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete it so the robot says its name.

  3. 3. Find the bug

    This program should print Woof! Which line has the error?

  4. 4. Predict the output

    What does this code print?

  5. 5. Multiple choice

    What does the passed method do?

  6. 6. Predict the output

    What does this code print?

  7. 7. Find the bug

    This program should print 50. Which line has the error?

  8. 8. Complete the code

    Every fall costs the cat one life. Complete it so it prints 5.

  9. 9. Put the lines in order

    Put the lines in order so the cart keeps what you add to it, in that order.

  10. 10. Find the case that fails

    avg(grades) creates a Student with those grades and returns their average. With no grades, it should return 0. Which call does it fail on?

  11. 11. Predict the output

    The thermos holds 600 ml and each cup takes 250. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →