Class and Objects in Python With Examples

Have you ever wondered how programmers create amazing software? Well, one of the secrets lies in a magical concept called class and objects in Python. These building blocks help organize and structure code simply and efficiently.

Imagine being able to create templates for different things, like cars or animals, and then use those templates to make as many objects as you want. It’s like having a blueprint for creating unique instances.

In our blog post, we’ll explain everything about classes and objects in Python. Get ready to dive into the world of programming and unleash your creativity!

What is a Python class?

A class in programming is like a blueprint that defines the characteristics and behaviors of an object. It is a way to create a new data type that can have its own attributes (variables) and methods (functions). Think of a class as a blueprint for creating objects with similar properties and actions.

What is an object?

In programming, it’s like having something that follows a specific blueprint or plan called a class. Imagine a class as a recipe for creating objects. Each object made from that recipe has its own unique characteristics and abilities.

For example, if the class is “Car,” objects could be actual cars like a red sports car or a blue sedan. Each car object would have its own color, brand, and features. Objects allow us to work with and do things with the data and functions defined in the class. They bring the class to life, just like how a real car is created based on its design and specifications.

Creating a class in Python

To create a class in Python, you use the class keyword followed by the name of the class. Inside the class, you define attributes (variables) and methods (functions) that will belong to the class.

Example

class ClassName:
    # Class attributes and methods go here
    pass

The init() Method

The init() method is a special method called the constructor. It is used to initialize the attributes of an object when it is created from the class. The self parameter refers to the object being created.

Example

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

In the above example, the Person class has an __init__() method that takes name and age as parameters. Inside the method, self.name and self.age are instance variables that store the values passed during object creation.

Class Variables

Class variables are variables that are shared among all instances of a class. They are defined within the class but outside any methods. Class variables are accessed using the class name, rather than an instance of the class.

Example

class Circle:
    pi = 3.14

In the above example, pi is a class variable that can be accessed as Circle.pi.

Instance Variables

Instance variables are unique to each instance of a class. They are defined within the init() method using the self parameter. Instance variables hold data that is specific to each object.

Example

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

    def greet(self):
        print(f"Hello, my name is {self.name}!")

In the above example, the greet() method is defined within the Student class. It can be called on a specific student object, such as student.greet(), to display a personalized greeting.

Working with Objects in Python

To create an object in Python, you need to instantiate it from a class. This is done by calling the class as if it were a function, which returns a new object.

For example:

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

my_dog = Dog("Buddy")

In the above example, we create an object my_dog of the Dog class by calling Dog("Buddy"). The name parameter is passed to the constructor (__init__() method) to initialize the name attribute of the object.

Accessing Object Attributes

Once an object is created, you can access its attributes using dot notation. This allows you to retrieve or modify the values stored in the object’s attributes.

Example:

print(my_dog.name)  # Output: Buddy
my_dog.name = "Max"
print(my_dog.name)  # Output: Max

In the above example, we access the name attribute of the my_dog object using my_dog.name. We can assign a new value to my_dog.name to update the attribute.

Calling Object Methods

Objects can have methods, which are functions defined within the class. To call a method on an object, you use dot notation, followed by the method name and parentheses.

Example:

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

    def meow(self):
        print(f"{self.name} says meow!")

my_cat = Cat("Whiskers")
my_cat.meow()  # Output: Whiskers says meow!

In the above example, we define a Cat class with an __init__() method and a meow() method. We create a my_cat object and call the meow() method using my_cat.meow().

Example 1: Python class represents a person

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

    def greet(self):
        print(f"Hello, my name is {self.name}.")

    def celebrate_birthday(self):
        self.age += 1
        print(f"It's my birthday! I am now {self.age} years old.")

# Creating a person object
person = Person("Aman", 25)

# Accessing attributes
print(person.name)  # Output: Aman
print(person.age)   # Output: 25

# Calling methods
person.greet()               # Output: Hello, my name is Aman.
person.celebrate_birthday()  # Output: It's my birthday! I am now 26 years old.

Output:

Aman
25
Hello, my name is Aman.
It's my birthday! I am now 26 years old.

In the above example, we define a class called “Person” with attributes like “name” and “age”. The __init__() method is used to initialize these attributes when a new person object is created. The class also has methods like “greet()” and “celebrate_birthday()” to represent actions a person can perform.

We create a person object called person with the name “Aman” and age 25. We can access its attributes using dot notation (person.name and person.age) and call its methods (person.greet() and person.celebrate_birthday()).

Example 2: Python class represents a car

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

    def start_engine(self):
        if self.is_running:
            print("The engine is already running.")
        else:
            self.is_running = True
            print("The engine has started.")

    def stop_engine(self):
        if self.is_running:
            self.is_running = False
            print("The engine has stopped.")
        else:
            print("The engine is already stopped.")

# Creating a car object
my_car = Car("Buggati", "Centodieci", 2023)

# Accessing attributes
print(my_car.make)   # Output: Buggati
print(my_car.model)  # Output: Centodieci
print(my_car.year)   # Output: 2023

# Calling methods
my_car.start_engine()   # Output: The engine has started.
my_car.stop_engine()    # Output: The engine has stopped.
my_car.start_engine()   # Output: The engine has started.

Output:

Buggati
Centodieci
2023
The engine has started.
The engine has stopped.
The engine has started.

In the above example, we define a class called “Car” with attributes like “make”, “model”, and “year”. The __init__() method is used to initialize these attributes when a new car object is created. The class also has methods like “start_engine()” and “stop_engine()” to represent actions a car can perform.

We create a car object called my_car with the make “Buggati”, model “Centodieci”, and year 2023. We can access its attributes using dot notation (my_car.make, my_car.model, and my_car.year) and call its methods (my_car.start_engine() and my_car.stop_engine()).

Example 3: Python class represents a book

In this, we take the example of the famous book, “The Late Americans” by Brandon Taylor, which was really awesome.

class Book:
    def __init__(self, title, author, publication_date):
        self.title = title
        self.author = author
        self.publication_date = publication_date
        self.is_available = True

    def check_out(self):
        if self.is_available:
            self.is_available = False
            print(f"The book '{self.title}' by {self.author} has been checked out.")
        else:
            print(f"The book '{self.title}' by {self.author} is already checked out.")

    def return_book(self):
        if not self.is_available:
            self.is_available = True
            print(f"The book '{self.title}' by {self.author} has been returned.")
        else:
            print(f"The book '{self.title}' by {self.author} is already available.")

# Creating a book object
my_book = Book("The Late Americans", "Brandon Taylor", "May 23")

# Accessing attributes
print(my_book.title)             # Output: The Late Americans
print(my_book.author)            # Output: Brandon Taylor
print(my_book.publication_date)  # Output: May 23

# Calling methods
my_book.check_out()              # Output: The book 'The Late Americans' by Brandon Taylor has been checked out.
my_book.return_book()            # Output: The book 'The Late Americans' by Brandon Taylor has been returned.
my_book.check_out()              # Output: The book 'The Late Americans' by Brandon Taylor has been checked out.

Output:

The Late Americans
Brandon Taylor
May 23
The book 'The Late Americans' by Brandon Taylor has been checked out.
The book 'The Late Americans' by Brandon Taylor has been returned.
The book 'The Late Americans' by Brandon Taylor has been checked out.

In this example, the Book class now represents the book titled “The Late Americans” by Brandon Taylor, published on May 23. The class’s attributes include title, author, and publication_date. The methods check_out() and return_book() allow for checking out and returning the book, respectively.

The book object my_book contains the specific information about “The Late Americans.” You can access its attributes using dot notation (my_book.title, my_book.author, and my_book.publication_date) and call its methods (my_book.check_out() and my_book.return_book()).

Create Multiple class & Objects of Python Class

This example demonstrates the creation of multiple classes and objects in Python, allowing us to represent and work with different entities with their own unique attributes and behaviors.

class Bike:
    def __init__(self, name, engine, model, cc):
        self.name = name
        self.engine = engine
        self.model = model
        self.cc = cc

    def display_info(self):
        print(f"This is a {self.name} {self.model} bike with a {self.cc}cc {self.engine} engine.")

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

    def display_info(self):
        print(f"This is a {self.year} {self.make} {self.model} car with a {self.cc}cc engine.")

# Creating objects of different classes
bike1 = Bike("Honda Shine", "BS6.2 engine", 2023, "125")
car1 = Car("Honda", "City", 2023, "1498")
car2 = Car("Tesla", "Model 3", 2022, "Electric")

# Calling methods for each object
bike1.display_info()   # Output: This is a Honda Shine 2023 bike with a 125cc BS6.2 engine.
car1.display_info()    # Output: This is a 2023 Honda City car with a 1498cc engine.
car2.display_info()    # Output: This is a 2022 Tesla Model 3 car with a Electriccc engine.

Output:

This is a Honda Shine 2023 bike with a 125cc BS6.2 engine engine.
This is a 2023 Honda City car with a 1498cc engine.
This is a 2022 Tesla Model 3 car with a Electriccc engine.

In this updated example, we have added the classes Bike and Car. Each class has its own attributes and a display_info() method to display information about the bike or car.

We create objects of these classes: bike1 representing a Honda Shine bike, car1 representing a Honda City car, and car2 representing a Tesla Model 3 car.

By calling the display_info() method for each object, we can retrieve specific information about each bike and car.

Leave a Comment