Section Overview
This section introduces you to the basics of object-oriented programming (OOP) in Python. You’ll learn how to create your own classes to model real-world things and organize your code into objects.
By the end of this section, you should be able to:
- Understand what classes and objects are
- Define a class with attributes and methods
- Create objects (instances) of a class
- Use object properties and call methods
Lesson 1: What is a Class?
A class is like a blueprint for creating objects. It defines attributes (data) and methods (functions) that belong to the objects.
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
Lesson 2: Creating Objects
You create an object (instance) by calling the class name like a function:
my_dog = Dog("Buddy", 3)
my_dog.bark()
Output:
Buddy says woof!
Lesson 3: The __init__
Method
__init__
is a special method called a constructor. It runs automatically when a new object is created and initializes the object’s attributes.
Lesson 4: Accessing Attributes and Methods
You access attributes and methods using dot notation:
print(my_dog.name) # Outputs: Buddy print(my_dog.age) # Outputs: 3
my_dog.bark() # Calls the bark method
Quiz: Check Your Understanding
1. What is an object?
Answer: An instance of a class representing a real-world thing.
2. What special method is called when an object is created?
Answer: __init__
3. How do you define a method inside a class?
Answer: By defining a function with def
inside the class.
4. What does self
represent inside a class method?
Answer: The instance (object) itself.
Practice Exercise: Create a Car
Class
Write a class called Car
that has:
- Attributes:
make
, model
, and year
- A method
display_info()
that prints out the car’s details
Then create two Car
objects and call display_info()
on each.
Starter code:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.make} {self.model}")
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Accord", 2018)
car1.display_info()
car2.display_info()