Week 12: Introduction to Object-Oriented Programming

Get a taste of object-oriented programming in Python.

Explore Chapter 12

Chapter 12: Basics of OOP in Python

Introduction to Classes and Objects.

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects." An object is a self-contained entity that combines data and behavior. OOP provides a way to structure your code in a more organized and modular way, making it easier to manage complex systems.

Classes

A class is a blueprint or a template for creating objects. It defines the attributes (data) and methods (behavior) that objects of that class will have. Think of a class as a cookie cutter, and objects as the cookies made from that cutter.

Objects

An object is an instance of a class. It's a concrete realization of the class blueprint. When you create an object, you are allocating memory to store the object's data and you can then interact with the object using its methods.

Defining a Class

class Dog:
    # Class attributes (data)
    species = "Canis familiaris"

    # Constructor (special method to initialize objects)
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    # Method (behavior)
    def bark(self):
        print("Woof!")

Creating Objects

my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Lucy", "Poodle")

Attributes and Methods.

Classes define the attributes and methods that their objects will possess.

Attributes

Attributes are variables that hold data associated with an object. They represent the state of an object. There are two main types of attributes:

  • Instance attributes: Belong to a specific instance (object) of the class. Each object has its own copy of instance attributes. In the `Dog` class, `name` and `breed` are instance attributes.
  • Class attributes: Belong to the class itself. They are shared by all instances of the class. In the `Dog` class, `species` is a class attribute.

You access instance attributes using the dot notation: `object.attribute`.

print(my_dog.name)  # Output: Buddy
print(your_dog.breed) # Output: Poodle
print(Dog.species)   # Output: Canis familiaris

Methods

Methods are functions that are defined inside a class and operate on objects of that class. They define the behavior of objects. Methods can access and modify the object's attributes.

You call methods using the dot notation: `object.method()`.

my_dog.bark()  # Output: Woof!

The `__init__` Method (Constructor)

The `__init__` method is a special method called the constructor. It is automatically called when you create a new object of the class. Its purpose is to initialize the object's attributes.

The `self` Parameter.

The `self` parameter is the first parameter in every instance method definition. It's a reference to the instance of the class (the object itself). When you call a method on an object, Python automatically passes the object itself as the first argument to the method, and that argument is assigned to the `self` parameter.

You use `self` to access the object's attributes and call other methods on the object from within the method.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

person1 = Person("Alice", 28)
person1.greet()  # Output: Hello, my name is Alice and I am 28 years old.

Although you can name the first parameter of an instance method something other than `self`, it is a strong convention to always use `self`, and you should stick to it.

Basic Concepts of Encapsulation.

Encapsulation is one of the fundamental principles of OOP. It involves bundling the data (attributes) and methods that operate on that data within a single unit (an object), and restricting direct access to some of the object's internal components.

Why Encapsulation?

  • Data hiding: Prevents accidental modification of data from outside the object.
  • Modularity: Makes code more modular and easier to maintain.
  • Abstraction: Hides the internal complexity of an object and exposes only the necessary interface.

Example (Simple Concept)

In Python, encapsulation is achieved through conventions (like using single or double underscores to indicate "protected" or "private" attributes), rather than strict access modifiers like in some other languages. We'll show a basic idea here.

class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Convention: _balance is "protected"

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount

    def get_balance(self):
        return self._balance

account = BankAccount(1000)
account.deposit(500)
print("Balance:", account.get_balance())  # Output: Balance: 1500

# While you *can* still do this, it's discouraged:
# account._balance = -1000  # Direct access is generally avoided

This is a very brief introduction. OOP is a large topic, and we've only scratched the surface. There's much more to learn about inheritance, polymorphism, and other OOP concepts.

Syllabus