A method is a function defined inside a class. It works on one object — the object it is called on, available in the body as self:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def is_square(self):
return self.width == self.height
Methods are called with a dot, like the list and string methods you have used all course — those were methods of exactly this kind:
r = Rectangle(3, 4)
print(r.area())
print(r.is_square())
Output:
12
False
r.area() runs area with self set to r, so self.width is 3. Every method's first parameter is self; the call site never passes it.
The difference from a plain function: area(r) would need the rectangle handed to it, while r.area() belongs to the object — data and the operations on that data live together in one definition.
Extend the Movie class from the previous lesson.
__init__ stores title, year, and runtime, as before.is_long that returns True when runtime is over 120 minutes.age_in with one parameter, current_year. It returns how many years old the movie is in that year.Movie("Alien", 1979, 117).age_in(2026) returns 47.
Run your code to see the output, then press Submit.
import unittest
class TestMovieMethods(unittest.TestCase):
def test_117_minutes_is_not_long(self):
self.assertIs(Movie("Alien", 1979, 117).is_long(), False)
def test_121_minutes_is_long(self):
self.assertIs(Movie("Solaris", 1972, 167).is_long(), True)
def test_exactly_120_minutes_is_not_long(self):
self.assertIs(Movie("X", 2000, 120).is_long(), False)
def test_age_in_2026(self):
self.assertEqual(Movie("Alien", 1979, 117).age_in(2026), 47)
def test_age_in_release_year_is_zero(self):
self.assertEqual(Movie("Alien", 1979, 117).age_in(1979), 0)
class Movie:
def __init__(self, title, year, runtime):
self.title = title
self.year = year
self.runtime = runtime
def is_long(self):
return self.runtime > 120
def age_in(self, current_year):
return current_year - self.year
movie = Movie("Alien", 1979, 117)
print(movie.is_long())
print(movie.age_in(2026))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.