Defining Classes
in Python
Learn how to create blueprints for objects using Python classes, define attributes and methods, and instantiate your own custom types.
What Is a Class?
A class is a blueprint or template that defines what data an object holds and what actions it can perform. Think of it like an architectural plan: the plan itself is not a house, but you can build many houses from the same plan.
Classes vs Instances
Why Use Classes?
The class Keyword
The __init__ Method
Understanding self
Class vs Instance Attributes
| Class Attribute | Instance Attribute | |
|---|---|---|
| Defined where? | Directly in the class body | Inside __init__ with self |
| Shared? | Yes: all instances share it | No: unique per instance |
| Example | species = "Canine" | self.name = name |
| Changed via | ClassName.attr | instance.attr |
Defining Methods
How to Define and Use a Class
Example 1: Student Class
Example 2: BankAccount
Example 3: Tracking Instances
Common Mistakes
Summary of Key Concepts
| Concept | Syntax | Purpose |
|---|---|---|
| Define a class | class Name: | Create a new type |
| Initializer | def __init__(self, ...): | Set up instance data |
| Instance attribute | self.attr = value | Store unique data |
| Method | def method(self): | Define behavior |
| Create instance | obj = Name(args) | Build an object |
| Access attribute | obj.attr | Read/modify data |
Question 1 of 5
Which keyword is used to define a new class in Python?
Question 2 of 5
What is the purpose of the __init__ method?
Question 3 of 5
Consider the following code:
class Car:
def __init__(self, make, year):
self.make = make
self.year = year
my_car = Car("Toyota", 2022)
What does my_car.make evaluate to?
Question 4 of 5
Consider this class:
class Counter:
total = 0
def __init__(self):
Counter.total += 1
a = Counter()
b = Counter()
c = Counter()
What is the value of Counter.total after all three instances are created?
Question 5 of 5
A student writes this code:
class Pet:
def __init__(self, name):
name = name
my_pet = Pet("Luna")
print(my_pet.name)
What happens when this code runs?