Summary - Classes
- Python course
- Intermediate
- Lesson 6/116
- 5 min
Combine attributes and methods to write a User class.
Summary - Classes
In this group you learned to define a class in Python, add attributes, write methods, set up instances with the constructor (__init__), and finally produce human readable output with __str__.
A class starts with class, the body is indented after a colon. __init__ runs when an instance is created; self points to the instance. __str__ is called by print. Now we will combine these into one class.
Practice Combine the Student class
Define a class named Student. Add def __init__(self, name): and write self.name = name in the body. Add def __str__(self): and write return f"Student: {self.name}". Then create an instance with s = Student("Dana") and write print(s).
Starter code
# Define the Student class with __init__ and __str__Sample solution
# Define the Student class with __init__ and __str__
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Student: {self.name}"
s = Student("Dana")
print(s)Expected output
Student: Dana
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which order should we proceed?
- __str__ → class → __init__
- class → __init__ → __str__ Correct answer
- __init__ → __str__ → class
- __str__ → __init__ → class
Explanation: First the class skeleton, then __init__, last __str__.
2 Match the concepts
| Term | Meaning |
|---|---|
class |
Template definition |
__init__ |
Constructor |
__str__ |
Readable output |
3 Complete the constructor body
class Student:
def __init__(self, name):
____ = name
class Student:
def __init__(self, name):
self.name = name
Explanation: The self.name assignment sets the instance attribute.