Chapter 9: Object-Oriented Programming / Lesson 47

Classes and Objects

Introduction to Classes and Objects

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects. A class is a blueprint for creating objects, and an object is an instance of a class. OOP helps organize code, make it reusable, and model real-world concepts.

Classes allow you to bundle data (attributes) and functions (methods) together, making your code more organized and easier to maintain.

Defining a Class

Use the class keyword to define a class. The __init__ method is a special method called when an object is created:

defining_class.py
# Define a class class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(f"{self.name} says Woof!") def get_info(self): return f"{self.name} is {self.age} years old" # Create objects (instances) dog1 = Dog("Buddy", 3) dog2 = Dog("Max", 5) # Use the objects dog1.bark() # Buddy says Woof! print(dog2.get_info()) # Max is 5 years old

Attributes and Methods

Attributes store data, and methods are functions that belong to the class:

attributes_methods.py
class Person: def __init__(self, name, age): # Attributes self.name = name self.age = age # Method def introduce(self): print(f"Hi, I'm {self.name} and I'm {self.age} years old.") def have_birthday(self): self.age += 1 print(f"Happy birthday! {self.name} is now {self.age}.") person = Person("Alice", 25) person.introduce() # Hi, I'm Alice and I'm 25 years old. person.have_birthday() # Happy birthday! Alice is now 26. print(person.age) # 26

The self Parameter

The self parameter refers to the instance of the class. It's automatically passed when you call a method on an object:

self_parameter.py
class Car: def __init__(self, brand, model): self.brand = brand # self refers to this instance self.model = model def start(self): print(f"{self.brand} {self.model} is starting...") # When you call car.start(), Python automatically passes the car object as self car = Car("Toyota", "Camry") car.start() # self is automatically car

Best Practices

✅ Class Design Tips

• Use descriptive class names (PascalCase)

• Keep classes focused on a single responsibility

• Use __init__ to initialize attributes

• Always include self as the first parameter in methods

• Use methods to modify object state, not direct attribute access

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...