OOP – Methods, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
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.
PREVIOUS · MODULE 50OOP – __init__ Method
YOU ARE HERE · MODULE 51OOP – Methods
NEXT · MODULE 52OOP – String Representation (__str__)
What students will learn in this module
Every question in Module 51
Quick questions
- What is a method?AA standalone functionBA function defined inside a class
- What must be the first parameter of a method?AselfBthis
- dog.bark() do you pass self?ANo Python passes it automaticallyBYes
- Can methods access self.name?ANoBYes that's how they use object data
- Can methods return values?AYes just like regular functionsBNo methods can't return
Key terms
Students type the meaning of:
Methodselfobject.method()self.attribute
Match the pairs
def bark():Match it to what it doesdog.Bark()Match it to what it doesdef bark(self):Match it to what it doesself.nameMatch it to what it does'hello'.upper()Match it to what it does[1,2,2].count(2)Match it to what it doesFill in the blanks
class Dog: def bark(____): return 'Woof!'class Dog: def bark(self): return ____.name + ' says Woof!'dog = Dog('Rex') print(dog.____( ))class Counter: def ________(self): self.count = 0 def increment(self): self.count __ 1class 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))
