What is class and object in Python with example?

Let’s provide separate explanations and examples for classes and objects in Python:

Class in Python:

It encapsulates attributes (data) and methods (functions) that the objects of the class will have. Classes are essential for creating custom data types and organizing code in a modular and reusable way.

Example of a Class:

# Define a class named "Person"
class Person:
    # Class-level attribute (same for all instances)
    species = "Homo sapiens"

    # Constructor (initializer) method to set instance-level attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method to greet the person
    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# Create an object (instance) of the class "Person"
person1 = Person("Alice", 30)

# Accessing attributes of the object
print(person1.name)  # Output: "Alice"
print(person1.age)   # Output: 30

# Accessing class-level attribute (same for all instances)
print(person1.species)  # Output: "Homo sapiens"

# Call instance method on the object
print(person1.greet())  # Output: "Hello, my name is Alice and I am 30 years old."

Object in Python:

An object is an instance of a class—a concrete representation of the class blueprint with its own unique attribute values. When you create an object, it is allocated memory for its attributes and can use the methods defined in its class.

Example of an Object:

# Define a class named "Rectangle"
class Rectangle:
    # Constructor (initializer) method to set instance-level attributes
    def __init__(self, length, width):
        self.length = length
        self.width = width

    # Instance method to calculate the area of the rectangle
    def calculate_area(self):
        return self.length * self.width

# Create two objects (instances) of the class "Rectangle"
rectangle1 = Rectangle(5, 10)
rectangle2 = Rectangle(3, 8)

# Accessing attributes of the objects
print(rectangle1.length)  # Output: 5
print(rectangle2.width)   # Output: 8

# Call instance method on the objects
print(rectangle1.calculate_area())  # Output: 50
print(rectangle2.calculate_area())  # Output: 24

In this example, we defined a class Rectangle with attributes length and width, as well as a method calculate_area to compute the area of a rectangle.

We then created two rectangle objects, rectangle1 and rectangle2, each with its own unique length and width.

When we called the calculate_area method on these objects, they returned different results based on their attribute values.

An example of defining a simple class and creating objects from it:

Let’s create a new example using a different class. This time, let’s create a class called “Book” to represent books in a library, and we’ll create objects based on this class.

Class Example – Book:

# Define a class named "Book"
class Book:
    # Class-level attribute (same for all books)
    material = "Paper"

    # Constructor (initializer) method to set instance-level attributes
    def __init__(self, title, author, year_published):
        self.title = title
        self.author = author
        self.year_published = year_published

    # Instance method to get the book's details
    def get_details(self):
        return f"Title: {self.title}, Author: {self.author}, Year Published: {self.year_published}"

# Create two book objects (instances) of the class "Book"
book1 = Book("To Kill a Mockingbird", "Harper Lee", 1960)
book2 = Book("1984", "George Orwell", 1949)

# Accessing attributes of the book objects
print(book1.title)  # Output: "To Kill a Mockingbird"
print(book2.author)  # Output: "George Orwell"

# Accessing class-level attribute (same for all books)
print(book1.material)  # Output: "Paper"
print(book2.material)  # Output: "Paper"

# Call instance method on the book objects
print(book1.get_details())  # Output: "Title: To Kill a Mockingbird, Author: Harper Lee, Year Published: 1960"
print(book2.get_details())  # Output: "Title: 1984, Author: George Orwell, Year Published: 1949"

In this example, we created a class Book with attributes title, author, and year_published, as well as a method get_details to retrieve the book’s information.

We then created two book objects, book1 and book2, each with its own unique book details.

The class-level attribute material is shared among all book objects and remains constant for all instances of the class.

Read More;

  • Yaryna Ostapchuk

    I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

Leave a Comment