You are on page 1of 2

KS4 – Object-oriented programming Learner Activity sheet

Lesson 2 – Classes and objects

Activity 2 worksheet: Using getter


methods
To make use of information in our objects, we need to write
some methods that give us access to it. These are called
getters. They are essentially functions that can be called to
get information about our objects.

Use the information on this sheet to complete activity 2 in


your pairs.

Task 1 . Creating get methods

Below is the code that you should have in your Pet class:

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

A. Add the following method below your existing code that will return the name
of your pet:

def get_name(self):
return self.name

B. Using the method above as a guide, add two more methods to your code to
get the species of your pet and the description.

Page 1 Last updated: 25-01-21


KS4 – Object-oriented programming Learner Activity sheet
Lesson 2 – Classes and objects

Task 2 . Check the getters

A. Open up your mypet.py file.

from pets import Pet


my_cat=Pet("Fluffy", "Cat", “Black and white long haired.”)

print(my_cat.get_name())

A print statement has been added to test the get_name() method.

B. Add print statements to test all of your getters are working.

Task 3 . Challenge

Instead of three separate print statements in your mypet.py file, we will use a different
approach to get information about our object.

Open up your pets.py file and add an additional method called describe() which will
print out the object’s attributes.

Below is an example of your mypet.py file calling the new describe method and the
related output:

from pets import Pet


my_cat=Pet("Fluffy", "Cat", “Black and white long haired.”)
my_cat.describe()

Output
Fluffy is a Cat. Black and white long haired.
>>>

Resources are updated regularly — the latest version is available at: ncce.io/tcc.

This resource is licensed under the Open Government Licence, version 3. For more information on this
licence, see ncce.io/ogl.

Page 2 Last updated: 25-01-21

You might also like