Putting it together
- Python course
- Intermediate
- Lesson 17/116
- 6 min
Combine helper methods into a single class.
Putting it together
In the final lesson we'll call all three helpers together. slugify tidies strings, clamp bounds numbers, format_date formats dates. All work on a single Utility instance.
We'll create one instance and call the three methods in turn: u = Utility(), u.slugify(...), u.clamp(...), u.format_date(...). Each call gives one line of output. This shows the library in action.
Three helpers in a row
We'll call the three helpers in turn and print each result on its own line. Each print call produces one line; the order is up to you.
Example output: hello-world, 10, 2024-05-01. These three lines show that the three different helpers work correctly. Each method deals with a different type (string, number, date) but they are all called on the same instance.
Practice Combine the three helpers
Keep the existing Utility class. On the instance u = Utility() call the three helpers in turn: print(u.slugify("Hello World")), print(u.clamp(15, 0, 10)) and print(u.format_date(2024, 5, 1)).
Starter code
class Utility:
version = "1.0"
def slugify(self, text):
return text.lower().replace(" ", "-")
def clamp(self, n, lo, hi):
return max(lo, min(hi, n))
def format_date(self, year, month, day):
return f"{year:04d}-{month:02d}-{day:02d}"
u = Utility()
print(u.format_date(2024, 5, 1))
# Call all helpers in turnSample solution
class Utility:
version = "1.0"
def slugify(self, text):
return text.lower().replace(" ", "-")
def clamp(self, n, lo, hi):
return max(lo, min(hi, n))
def format_date(self, year, month, day):
return f"{year:04d}-{month:02d}-{day:02d}"
u = Utility()
print(u.slugify("Hello World"))
print(u.clamp(15, 0, 10))
print(u.format_date(2024, 5, 1))Expected output
hello-world 10 2024-05-01
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which call works on a Utility instance?
- u.slugify("Hello") Correct answer
- Utility.slugify("Hello")
- slugify("Hello")
- u(Utility.slugify)
Explanation: Instance methods are called as u.method().
2 Match the helpers
| Term | Meaning |
|---|---|
slugify |
String helper |
clamp |
Number helper |
format_date |
Date helper |
3 Complete the slugify call
print(u.slugify(____))
print(u.slugify("Hello World"))
Explanation: The string argument is passed to slugify.