Objects and Classes in Python: Create, Modify and Delete

Understanding classes and objects in Python is fundamental to mastering object-oriented programming (OOP). Classes provide a blueprint for creating objects, encapsulating data, and defining behaviors for a specific object type. This article explores how to create, modify, and delete classes and objects in Python, offering a comprehensive guide to leveraging OOP principles in your programs. Whether you're a beginner looking to grasp the basics or an experienced programmer aiming to refine your skills, this guide will help you effectively utilize classes and objects in Python to write clean, modular, and efficient code. Dive in to learn how to define classes, instantiate objects, and manipulate their attributes and methods to harness the full power of Python's object-oriented capabilities.

Master Web Scraping, Django & More!

Python Certification CourseENROLL NOW
Master Web Scraping, Django & More!

Python Objects

Overview

Since everything in Python is an object, all data types and structures are just instances of a specific class. Objects are instances of classes that have functions (methods) to modify data and data (attributes). Understanding objects is essential to understanding the object-oriented programming (OOP) paradigm in Python. Using objects, you can define behaviors, encapsulate data, and model real-world entities—all of which encourage code reuse and modularity.

Syntax 

In Python, an object is created by instantiating an object from a defined class once the class has been defined. The fundamental syntax for declaring a class and producing an object is as follows:

class ClassName:
    # Constructor
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

    # Method
    def method_name(self):
        # Method body
        pass

# Creating an object of the class
object_name = ClassName(attribute1_value, attribute2_value)

Example

Here is a practical example that shows how to create and use objects in Python:

class Car:
    # Constructor to initialize attributes
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    # Method to display car details
    def display_info(self):
        print(f"{self.year} {self.make} {self.model}")

    # Method to update the model of the car
    def update_model(self, new_model):
        self.model = new_model

# Creating an object of the Car class
my_car = Car("Toyota", "Corolla", 2020)

# Accessing attributes
print(my_car.make)  # Output: Toyota
print(my_car.model)  # Output: Corolla
print(my_car.year)  # Output: 2020

# Calling methods
my_car.display_info()  # Output: 2020 Toyota Corolla

# Modifying attributes
my_car.update_model("Camry")
my_car.display_info()  # Output: 2020 Toyota Camry

Python Classes 

Overview

In Python, a class is an object creation blueprint. It specifies a collection of properties and functions that the objects (instances) produced will have. Classes encourage code organization, reuse, and modularity by encapsulating data and activities. You may model real-world items, specify their attributes, and control the complexity of your applications more effectively by using classes.

Syntax

The 'class' keyword, the class name, and a colon define a class in Python. The constructor that initializes an object's attributes is called the __init__ method, and it usually comes first in the class body of method definitions.

class ClassName:
    # Constructor method
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

    # Method
    def method_name(self):
        # Method body
        pass

# Creating an object of the class
object_name = ClassName(attribute1_value, attribute2_value)

Example

This is an illustration of how to define and use a class in Python:

class Dog:
    # Constructor to initialize attributes
    def __init__(self, name, age, breed):
        self.name = name
        self.age = age
        self.breed = breed

    # Method to display dog details
    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}, Breed: {self.breed}")

    # Method to update the age of the dog
    def update_age(self, new_age):
        self.age = new_age

# Creating an object of the Dog class
my_dog = Dog("Buddy", 3, "Golden Retriever")

# Accessing attributes
print(my_dog.name)  # Output: Buddy
print(my_dog.age)  # Output: 3
print(my_dog.breed)  # Output: Golden Retriever

# Calling methods
my_dog.display_info()  # Output: Name: Buddy, Age: 3, Breed: Golden Retriever

# Modifying attributes
my_dog.update_age(4)
my_dog.display_info()  # Output: Name: Buddy, Age: 4, Breed: Golden Retriever

The _init_Method

Overview

In Python, a particular method called a constructor is the '__init__' method. It is triggered automatically upon the creation of a new class instance. Initializing the object's attributes with the values supplied during instantiation is the primary goal of the '__init__' method. By giving an object's attribute values, you can establish its initial state.

Syntax

Like any other method, the '__init__' method is specified with the 'def' keyword. But '__init__' must be its name. The argument'self', which denotes the instance being created, is always required. Other parameters can be added to take values that initialize the object's attributes.

class ClassName:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

Example

This is an illustration of how to initialize an object's attributes using the '__init__' method:

class Person:
    def __init__(self, name, age):
        self.name = name  # Initializing the 'name' attribute
        self.age = age    # Initializing the 'age' attribute

    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}")

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

# Accessing attributes
print(person1.name)  # Output: Alice
print(person1.age)   # Output: 30

# Calling methods
person1.display_info()  # Output: Name: Alice, Age: 30

The __str__() Function

Overview 

When the 'str()' or 'print()' functions are used on an object in Python, a unique method known as '__str__()' is called. It gives the item a string representation, which improves readability and informational value. You can manage how a class's objects are represented as strings by creating the '__str__()' method in that class.

Syntax 

'self', the class instance, is the only parameter required for the '__str__()' method, which is declared with the 'def' keyword.

class ClassName:
    def __str__(self):
        return "string representation of the object"

Example

This is an illustration of how to create a valid string representation of an object using the '__str__()' method:

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

    def __str__(self):
        return f"Person(Name: {self.name}, Age: {self.age})"

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

# Using the str() function and print() function
print(person1)  # Output: Person(Name: Alice, Age: 30)
print(str(person1))  # Output: Person(Name: Alice, Age: 30)

Creating Classes and Objects in Python

Overview 

Classes in Python offer a template for building objects or instances of the class. Classes contain the behaviors (methods) and data (attributes) that specify the characteristics and capabilities of the objects. The foundation of object-oriented programming (OOP) in Python is the creation of classes and objects, which let you better manage the complexity of your programs and model real-world entities.

Syntax 

In Python, a class is defined using the 'class' keyword, the class name, and a colon. The constructor used to initialize an object's attributes, the '__init__' method, usually comes first in the class body of method declarations.

class ClassName:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

    def method_name(self):
        # Method body
        Pass

You invoke a class by its name and supply any necessary arguments to the constructor to create an object or an instance of a class.

object_name = ClassName(attribute1_value, attribute2_value)

Become a Full Stack Developer in Just 6 Months!

Full Stack Developer - MERN StackEXPLORE COURSE
Become a Full Stack Developer in Just 6 Months!

Example

This is an example that shows you how to create and use a class and its objects in Python:

# Defining a class named Car
class Car:
    # Constructor to initialize attributes
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    # Method to display car details
    def display_info(self):
        print(f"{self.year} {self.make} {self.model}")

    # Method to update the model of the car
    def update_model(self, new_model):
        self.model = new_model

# Creating an object of the Car class
my_car = Car("Toyota", "Corolla", 2020)

# Accessing attributes
print(my_car.make)  # Output: Toyota
print(my_car.model)  # Output: Corolla
print(my_car.year)  # Output: 2020

# Calling methods
my_car.display_info()  # Output: 2020 Toyota Corolla

# Modifying attributes
my_car.update_model("Camry")
my_car.display_info()  # Output: 2020 Toyota Camry

Access Class Attributes Using Objects

Overview

In Python, objects from the class are used to access class attributes, also called instance variables. You can read and change these attributes directly by using dot notation. This enables you to work with the data that the object contains.

Syntax

To access class attributes, use the object name, followed by a dot (. ), and the attribute name.

object_name.attribute_name

Example

This example shows how to define a class, make an object, and retrieve its properties:

# Defining a class named Person
class Person:
    # Constructor to initialize attributes
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

    # Method to display person details
    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}, City: {self.city}")

# Creating an object of the Person class
person1 = Person("Alice", 30, "New York")

# Accessing attributes
print(person1.name)  # Output: Alice
print(person1.age)   # Output: 30
print(person1.city)  # Output: New York

# Calling a method that accesses attributes
person1.display_info()  # Output: Name: Alice, Age: 30, City: New York

# Modifying attributes
person1.age = 31
print(person1.age)   # Output: 31

# Display updated information
person1.display_info()  # Output: Name: Alice, Age: 31, City: New York

Explanation

Boost Your Coding Skills. Nail Your Next Interview

Full Stack Developer - MERN StackExplore Program
Boost Your Coding Skills. Nail Your Next Interview

1. Defining the Class

The ‘Person’ class is defined with an ‘__init__’ method to initialize the attributes ‘name’, ‘age’, and ‘city’.

A method ‘display_info’ is defined to print the details of the person.

2. Creating an Object

The object ‘person1’ is created as an instance of the ‘Person’ class, with the initial values "Alice", 30, and "New York" for the attributes.

3. Accessing Attributes

The attributes ‘name’, ‘age’, and ‘city’ of the object ‘person1’ are accessed using dot notation (‘person1.name, person1.age, person1.city’).

4. Calling a Method

The ‘display_info’ method is called on ‘person1’ to print the details of the person. This method accesses the attributes of the object internally.

Master Web Scraping, Django & More!

Python Certification CourseENROLL NOW
Master Web Scraping, Django & More!

5. Modifying Attributes

The ‘age’ attribute of ‘person1’ is modified using dot notation (‘person1.age = 31’).

6. Displaying Updated Information

The updated information is displayed by repeatedly calling the ‘display_info’ method, showing the modified age.

Create Multiple Objects of Python Class

Overview 

You can instantiate and manage numerous instances of the same class in Python by creating multiple objects of that class. Every item can operate independently of other things and have distinct properties. This is helpful when you must maintain distinct states for various instances or model several real-world things.

Syntax 

All you have to do to create many objects is call the class multiple times with different arguments, allocating a distinct variable to each instance.

object1 = ClassName(attribute1_value, attribute2_value)
object2 = ClassName(attribute1_value, attribute2_value)

Example

This is an illustration showing how to define a class and make several objects out of it:

# Defining a class named Car
class Car:
    # Constructor to initialize attributes
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    # Method to display car details
    def display_info(self):
        print(f"{self.year} {self.make} {self.model}")

# Creating multiple objects of the Car class
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2019)
car3 = Car("Ford", "Mustang", 2021)

# Accessing attributes and calling methods on each object
car1.display_info()  # Output: 2020 Toyota Corolla
car2.display_info()  # Output: 2019 Honda Civic
car3.display_info()  # Output: 2021 Ford Mustang

# Modifying attributes for one of the objects
car2.model = "Accord"
car2.display_info()  # Output: 2019 Honda Accord

Explanation

1. Defining the Class

The ‘Car’ class is defined with an ‘__init__’ method to initialize the attributes ‘make’, ‘model’, and ‘year’.

A method ‘display_info’ is defined to print the details of the car.

2. Creating Multiple Objects

Three objects, ‘car1’, ‘car2’, and ‘car3’, are created as instances of the ‘Car’ class with different values for ‘make’, ‘model’, and ‘year’.

3. Accessing Attributes and Calling Methods

The ‘display_info’ method is called on each object to print their respective details.

4. Modifying Attributes

The ‘model’ attribute of ‘car2’ is modified to "Accord", and the updated information is displayed by calling ‘display_info’ again.

Skyrocket Your Career: Earn Top Salaries!

Python Certification CourseENROLL NOW
Skyrocket Your Career: Earn Top Salaries!

Conclusion 

Comprehending Python's classes and objects is essential to learning object-oriented programming, which is necessary for creating dependable and maintainable applications. Gaining knowledge about the creation, editing, and removal of objects can help you manage program complexity and adequately simulate real-world entities. Classes are the building blocks of objects; they allow for the construction of numerous distinct instances while enclosing behaviors and data.

If you grasp these ideas, you can build more readable, modular, and reusable code. Enrolling in Python Training can be helpful for people who want to learn more and obtain real-world experience. Furthermore, if you're seeking a more comprehensive skill set, consider enrolling in a Full Stack Developer - MERN Stack. This will provide you with an extensive understanding of both front-end and back-end development, making you a highly employable and versatile professional in the

FAQs

1. What Is Self in a Class?

'self' in Python refers to the instance of the class that is now in use and is used to access class variables. It enables you to access the properties and methods of the object to which the process is being called. It is the first parameter of any instance method in a class. 'self' is the standard name, though you can give it anything to adhere to Python norms and make the code easier to read.

You can call other class-defined methods and initialize the object's attributes using 'self'. It facilitates the distinction between local variables and instance characteristics.

Example

class Dog:
    def __init__(self, name, age):
        self.name = name  # Initialize instance attribute 'name'
        self.age = age    # Initialize instance attribute 'age'

    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}")

# Creating an object of the Dog class
my_dog = Dog("Buddy", 3)

# Accessing attributes and calling methods
print(my_dog.name)  # Output: Buddy
print(my_dog.age)   # Output: 3
my_dog.display_info()  # Output: Name: Buddy, Age: 3

2. What Are Class Attributes and Instance Attributes?

The two sorts of attributes in Python that specify the state of objects within a class are class attributes and instance attributes. Class properties have the same value for each instance since all class instances share them. They aren't defined inside any methods but within the class. Conversely, instance attributes are unique to each instance of the class, which means that various cases may have different values for them. Usually, they are defined in the '__init__' method and linked to the instance using the 'self' keyword.

Example

class Dog:
    # Class attribute
    species = "Canis familiaris"

    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age

# Creating objects of the Dog class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

# Accessing class attribute
print(dog1.species)  # Output: Canis familiaris
print(dog2.species)  # Output: Canis familiaris

# Accessing instance attributes
print(dog1.name, dog1.age)  # Output: Buddy 3
print(dog2.name, dog2.age)  # Output: Lucy 5

# Modifying the class attribute
Dog.species = "Canis lupus"
print(dog1.species)  # Output: Canis lupus
print(dog2.species)  # Output: Canis lupus

# Modifying the instance attribute
dog1.age = 4
print(dog1.age)  # Output: 4
print(dog2.age)  # Output: 5

3. What Is the Difference Between a Class Method and an Instance Method?

A class method and an instance method in Python differ primarily in what they work on and how they are written. An instance method can access and change the attributes of an object that is an instance of the class. It refers to the instance when defined with the'self' parameter. In contrast, a class method works on the class itself and has access to and control over class-level properties. The '@classmethod' decorator is used to define it, and the class is referenced by its first parameter, 'cls'.

Example

class Dog:
    # Class attribute
    species = "Canis familiaris"

    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old."

    # Class method
    @classmethod
    def set_species(cls, new_species):
        cls.species = new_species

# Creating an object of the Dog class
dog1 = Dog("Buddy", 3)

# Calling an instance method
print(dog1.description())  # Output: Buddy is 3 years old.

# Calling a class method
Dog.set_species("Canis lupus")
print(Dog.species)  # Output: Canis lupus
print(dog1.species)  # Output: Canis lupus

About the Author

Aryan GuptaAryan Gupta

Aryan is a tech enthusiast who likes to stay updated about trending technologies of today. He is passionate about all things technology, a keen researcher, and writes to inspire. Aside from technology, he is an active football player and a keen enthusiast of the game.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.