Skip to Content
Course content

5.1 Classes and Objects

In Python, classes and objects are the fundamental building blocks of Object-Oriented Programming (OOP). They allow you to structure your code in a more organized and reusable way, helping manage large and complex programs.

What Are Classes and Objects?

  • Class: A class is a blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that the objects created from the class will have. You can think of a class as a template for an object, which outlines what data an object will have and how that data can be manipulated.
  • Object: An object is an instance of a class. When you create an object from a class, you instantiate the class. Each object can have different values for the attributes defined in the class, but it will have the same methods to operate on that data.

Defining a Class

To define a class in Python, you use the class keyword, followed by the name of the class. The class body is indented and can contain attributes (variables) and methods (functions) that operate on those attributes.

Example:

class Car:
    # Initializer (Constructor)
    def __init__(self, make, model, year):
        self.make = make        # Instance attribute
        self.model = model      # Instance attribute
        self.year = year        # Instance attribute
    
    # Method to display information about the car
    def display_info(self):
        print(f"{self.year} {self.make} {self.model}")

# Creating an object (instance) of the Car class
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2021)

# Calling a method using the objects
car1.display_info()  # Output: 2020 Toyota Corolla
car2.display_info()  # Output: 2021 Honda Civic

In this example:

  • Car is a class with an initializer (__init__), which is a special method used to initialize objects.
  • self refers to the current instance of the class, allowing the instance to access its attributes and methods.
  • display_info() is a method that prints the details of the car.

Attributes in Classes

Attributes are variables that belong to a class or an object. They can be defined inside the class's methods, particularly in the __init__() method, which initializes the values of the object when it's created.

Example:

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

# Creating an instance of the class
dog = Animal("Buddy", "Dog")
print(dog.name)        # Output: Buddy
print(dog.species)     # Output: Dog
  • name and species are instance attributes because they belong to an instance (or object) of the class.

You can also define class attributes, which are shared across all instances of the class. For example:

class Dog:
    species = "Canine"  # This is a class attribute
    
    def __init__(self, name):
        self.name = name   # This is an instance attribute

# Creating instances
dog1 = Dog("Buddy")
dog2 = Dog("Bella")

print(dog1.species)  # Output: Canine
print(dog2.species)  # Output: Canine

Here, species is a class attribute, meaning it is shared across all instances of the Dog class.

Methods in Classes

A method is a function defined within a class. Methods operate on the data (attributes) contained in an object. In Python, methods take the self parameter as their first argument, which allows them to access and modify the instance's attributes.

Example:

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.")

# Creating an object of the Person class
person1 = Person("John", 30)
person1.greet()  # Output: Hello, my name is John and I am 30 years old.

In this example:

  • greet() is a method that prints a greeting using the object's attributes.

Creating Objects (Instances)

An object is an instance of a class. You can create objects by calling the class as if it were a function. This invokes the __init__() method, which initializes the object.

Example:

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

# Creating objects (instances) of the Car class
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2021)

Here, car1 and car2 are objects of the Car class, each with its own set of attributes.

Inheritance

Inheritance is a feature in OOP that allows a new class to inherit attributes and methods from an existing class. This helps in code reuse and establishing a relationship between classes.

Example:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound")

# Dog class inherits from Animal
class Dog(Animal):
    def speak(self):
        print(f"{self.name} barks")

# Creating an object of Dog class
dog = Dog("Buddy")
dog.speak()  # Output: Buddy barks

Here:

  • Dog is a subclass of Animal. It inherits the __init__() method from Animal but overrides the speak() method to provide a custom behavior.

Encapsulation

Encapsulation is the concept of restricting access to certain details of an object’s implementation. It is usually done by marking attributes as private and providing public methods to access them.

In Python, you can use a single underscore _ or double underscore __ to mark attributes as protected or private, respectively.

Example:

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if self.__balance >= amount:
            self.__balance -= amount
        else:
            print("Insufficient funds")

    def get_balance(self):
        return self.__balance

# Creating an object of BankAccount
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())  # Output: 1300

In this example, __balance is a private attribute, and access to it is provided through methods like deposit(), withdraw(), and get_balance().

Polymorphism

Polymorphism allows objects of different classes to be treated as instances of the same class through a common interface. It means the same method or function can behave differently depending on the object that calls it.

Example:

class Animal:
    def speak(self):
        print("Animal makes a sound")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

class Cat(Animal):
    def speak(self):
        print("Cat meows")

# Polymorphism in action
animals = [Dog(), Cat()]
for animal in animals:
    animal.speak()  # Output: Dog barks \n Cat meows

Here, the speak() method behaves differently depending on the type of object calling it (Dog or Cat).

Conclusion

  • Classes define the structure and behavior of objects.
  • Objects are instances of classes and can have attributes and methods that are specific to them.
  • Python’s class-based structure supports OOP concepts like inheritance, encapsulation, and polymorphism, making it powerful for building organized and scalable applications.

Commenting is not enabled on this course.