OOP – Methods, online

Six activities your students do on their own devices. See who's finished, and their scores.

OOP – Methods in one minute

What students need to know

self refers to the object the method is called on. self.name reads the name attribute of the current object.

Methods are functions that belong to a class and operate on its objects. Python uses self — other languages use this, but Python convention is self.

Mistakes students make

  • Missing self parameter every method needs self as first parameter.
  • Use self.name inside methods name alone is not defined here.
  • Missing parentheses bark is a method, call it with ().
  • Call methods on objects, not the class. Create an object first.

Discover other journeys with this module

What students will learn in this module

Every question in Module 51

Quick questions

  1. What is a method?AA standalone functionBA function defined inside a class
  2. What must be the first parameter of a method?AselfBthis
  3. dog.bark() do you pass self?ANo Python passes it automaticallyBYes
  4. Can methods access self.name?ANoBYes that's how they use object data
  5. Can methods return values?AYes just like regular functionsBNo methods can't return

Key terms

Students type the meaning of:

  • Method
  • self
  • object.method()
  • self.attribute

Match the pairs

def bark():Match it to what it does
dog.Bark()Match it to what it does
def bark(self):Match it to what it does
self.nameMatch it to what it does
'hello'.upper()Match it to what it does
[1,2,2].count(2)Match it to what it does

Fill in the blanks

  1. class Dog:
        def bark(____):
            return 'Woof!'
  2. class Dog:
        def bark(self):
            return ____.name + ' says Woof!'
  3. dog = Dog('Rex')
    print(dog.____(  ))
  4. class Counter:
        def ________(self):
            self.count = 0
        def increment(self):
            self.count __ 1
  5. class Circle:
        def area(self):
            ______ 3.14 * self.radius ** 2

Spot the error

Question 1

Aclass Dog:B    def bark():C        return 'Woof!'

Question 2

Aclass Dog:B    def __init__(self, name):C        self.name = nameD    def bark(self):E        return name + ' says Woof!'

Question 3

Adog = Dog('Rex')Bdog.bark

Question 4

Aclass Dog:B    def bark(self):C        return 'Woof!'DEDog.bark()

Question 5

Aclass Dog:B    def bark(self):C        return 'Woof!'DEdog = Dog()Fprint(dog.bark(self))