41
Classes & Objects
Classes: Bundling Data and Behavior Together
What might confuse you right now
"I already know functions. Why do I need classes?"
Functions are great for processing steps. Classes are great for modeling "object state + behavior."
One-line definition
A class is a template for creating objects. Objects have attributes (data) and methods (behavior).
Real-life analogy
A class is like a "student record template." An object is "one specific student."
Minimal runnable example
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def is_pass(self):
return self.score >= 60
s = Student("Amy", 85)
print(s.is_pass())
Quick quiz (5 min)
- Define a
Bookclass (title, price). - Write an
is_expensive()method. - Create two objects and test them.
Quiz answer guidelines & grading criteria
- Answer direction: working code that covers core conditions and edge inputs from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Transfer task (homework)
Convert your "user dictionary processing script" into a User class version.
Acceptance criteria
You can independently:
- Define a class with an init method
- Create objects and call methods
- Distinguish between attribute and method responsibilities
Common errors & debugging steps (beginner edition)
- Can't understand the error: read the last line for the error type (e.g.,
TypeError,NameError), then trace back to the relevant code line. - Not sure about a variable's value: temporarily add
print(variable, type(variable))at key points to verify data matches expectations. - Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.
Common misconceptions
- Misconception: Classes are just syntactic sugar.
- Reality: Classes solve the modeling problem of binding state and behavior together.