Methods
- Python course
- Intermediate
- Lesson 3/116
- 4 min
Learn methods and self inside a class.
Defining methods
A method is a function defined inside a class. A method starts with def; its first parameter is always self.
Example: class Book:\n def describe(self):\n print("Book"). Here describe is the method name; self points to the instance. Defining a method does not run it; it waits to be called: b.describe().
The self parameter
self points to the instance that calls the method. Inside a method you access instance data with self.attribute. The call does not pass self explicitly; Python sends it automatically.
Example: b = Book(); b.describe(). Here describe(self) is called with self being the instance b. This way the method uses the right instance's data. Another name could replace self, but self is the convention.
Practice Add a method to the Book class
Define a class named Book. Add a method def describe(self): whose body is print("Book"). After the class, create an instance with b = Book() and call b.describe().
Starter code
# Define the Book class and the describe methodSample solution
# Define the Book class and the describe method
class Book:
def describe(self):
print("Book")
b = Book()
b.describe()Expected output
Book
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the parts of a method
| Term | Meaning |
|---|---|
def |
Keyword |
describe |
Method name |
self |
Instance reference |
2 What is the first parameter of a method?
- cls
- this
- self Correct answer
- instance
Explanation: An instance method's first parameter is self; the instance is passed automatically.
3 Complete the method signature
class Book:
def describe(____):
print("Book")
class Book:
def describe(self):
print("Book")
Explanation: An instance method's first parameter is self.