Introduction
So far, you’ve learned how to:
- Create classes
- Use
__init__to store data - Use
selfto give each object its own attributes
In this lesson, you’ll learn how to:
- Define methods inside a class
- Use
selfto access object data inside methods - Call methods on objects
Methods allow objects to do things, not just store data.
What Is a Method?
A method is a function that belongs to a class.
It is:
- Defined inside a class
- Automatically given access to the object using
self
Example: A Method Inside a Class
class Student:
def __init__(self, name):
self.name = name
def say_hello(self):
print('Hello, my name is', self.name)
student = Student('Alex')
student.say_hello()
What’s happening here?
say_hellois a methodself.nameaccesses data stored in the object- The method is called using dot notation
Predict:
Look at the following code. What do you think will be printed?
class Student:
def __init__(self, name):
self.name = name
def introduce(self):
print('My name is', self.name)
student1 = Student('Alex')
student2 = Student('Jamie')
student1.introduce()
student2.introduce()
Think about:
- Will both students print the same message?
- How does the method know which name to use?
Run:
Run the code below and check your prediction.
Investigate:
Now let’s explore what happens when a method uses more than one attribute.
Try this:
- Add an attribute called
year_group - Update the method so it prints both the name and year group
Use the editor below to experiment.
Think about:
- Why does the method not need parameters for
name? - How does
selfhelp the method access the correct data?
Modify:
The following code contains a mistake — the method cannot access the object’s data correctly.
Fix the code so the method works as intended.
The problem
- The method is missing
self - Python doesn’t know which object is being used
Hint:
Methods must always include self as the first parameter.