Creating an Object in Python

In Python, an object is an instance of a class. Objects are created by calling the class itself, and they hold the data (attributes) and behavior (methods) defined within the class. Understanding how to create and use objects is a fundamental concept in Python's object-oriented programming.



Creating an Object (Instance) of a Class

In Python, the process of creating an object from a class is called instantiating the class. This is done by calling the class name as if it were a function, passing any arguments required by the class's __init__ method. Once an object is created, it can access the methods and attributes of the class.

Syntax for Creating an Object

The syntax to create an object is simple:

python
object_name = ClassName(arguments)

After creating the object, you can use dot notation to access the object's attributes and methods.


Creating an Object and Accessing Methods and Variables

Once you've defined a class, you can create an instance (or object) of that class. After creating the object, you can access the class's attributes (variables) and methods. Let's look at an example where we create a Car class, instantiate an object, and access its attributes and methods.

1. Define the Class

We'll start by defining a Car class with some basic attributes like make, model, and year. We'll also add a method that displays the car's information.

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

    def display_info(self):
        print(f"{self.year} {self.make} {self.model}")

2. Create an Object (Instance) from the Class

Now that we have the class defined, we can create an object from this class by calling the class and passing the necessary arguments to the constructor (the __init__ method). Let's create an object for a car.

python
# Create an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)

3. Access the Object's Attributes and Methods

Now that we have our object my_car, we can access its attributes and methods.

Accessing Attributes

We can access the car's attributes like make, model, and year by using the dot notation.

python
# Accessing attributes
print(my_car.make)   # Output: xyz_maker
print(my_car.model)  # Output: xyz_model
print(my_car.year)   # Output: 2025

Accessing Methods

We can also call the display_info() method to print the information about the car.

python
# Calling a method
my_car.display_info()  # Output: 2025 xyz_maker xyz_model

This example shows how we can create an object from a class and access both its attributes and methods. The class encapsulates the data (the car's make, model, and year) and the behavior (displaying the car's information), making it easier to manage and interact with.


Object Lifespan and Memory Management in Python

In Python, once an object is created, it occupies memory until it is no longer needed. Understanding how Python handles object memory and the lifespan of objects is important for efficient memory management, especially in larger applications. In this section, we'll discuss how Python manages memory for objects and what happens when they are no longer needed.

Object Creation and Memory Allocation

When an object is created by calling a class (i.e., instantiating the class), Python allocates memory for that object. The attributes and methods defined in the class are stored within this memory space. The object remains in memory as long as there is a reference pointing to it.

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

# Create an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)

In the example above, the object my_car is created and occupies memory. As long as there is a reference to my_car, the object will not be deleted.

When Does an Object Get Destroyed?

Objects in Python are automatically destroyed when they are no longer referenced by any variable. This means that when there are no more references pointing to an object, Python's garbage collector will free up the memory allocated to that object.

Example: Object with No References

Let's say you delete all references to an object. When no references exist, the object becomes eligible for garbage collection, and Python will free up the memory.

python
# Create an instance of the Car class
my_car = Car("xyz_maker", "xyz_model", 2025)

# Remove the reference to the object
del my_car
# Now, the object is no longer referenced, and Python will delete it automatically.

In this example, we created an object and then removed the reference to it using the del keyword. Once the reference to the object is deleted, Python will handle the cleanup and memory deallocation.

Garbage Collection in Python

Python uses a garbage collection mechanism to automatically manage memory. When an object has no references pointing to it, the garbage collector will reclaim the memory associated with that object. Python uses reference counting and cyclic garbage collection to ensure memory is freed when no longer needed.

Reference Counting

Python keeps track of how many references exist to each object. Each time a reference to an object is created or destroyed, the reference count is updated. When an object's reference count reaches zero, it is immediately destroyed. This is the primary way Python handles memory management.

Cyclic Garbage Collection

While reference counting works well for most objects, it has limitations when objects reference each other in a cycle (e.g., object A references object B, and object B references object A). This would prevent the reference count from ever reaching zero, potentially leading to memory leaks.
To handle this, Python has a cyclic garbage collector that can detect and clean up these cycles automatically. The garbage collector runs periodically in the background to reclaim memory from cyclic references.

Memory Management Example: Cyclic Garbage Collection

Here’s an example to illustrate how cyclic references might occur and how Python handles them with garbage collection.

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

# Create two car objects
car1 = Car("xyz_maker", "xyz_model", 2025)
car2 = Car("Honda", "Civic", 2022)

# Create a cyclic reference
car1.partner = car2
car2.partner = car1

# Now, car1 and car2 reference each other. If we remove all external references,
# Python's garbage collector will detect the cycle and free their memory.

In the example above, car1 and car2 reference each other, forming a cycle. Even though we no longer have any external references to them, Python's garbage collector will eventually clean up these objects.

Conclusion

Understanding object lifespan and memory management in Python is important for writing efficient and optimized code. Python's automatic memory management, using reference counting and garbage collection, helps ensure that objects are deleted when no longer needed, freeing up memory. As a developer, you can rely on Python's garbage collector to handle memory management most of the time, but it's important to be aware of how it works, especially when dealing with circular references or resource-heavy objects.


Frequently Asked Questions

What is an object in Python?

An object in Python is an instance of a class. It holds the data (attributes) and behavior (methods) defined in the class.


How do you create an object in Python?

To create an object, call the class name followed by parentheses and any required arguments. For example: my_car = Car("xyz_maker", "xyz_model", 2025).


How do you access attributes and methods of an object?

Use dot notation to access attributes and methods. For example: my_car.make or my_car.display_info().


When is an object in Python destroyed?

An object is destroyed when there are no more references to it. Python’s garbage collector then deallocates its memory automatically.


What is the role of the __init__ method in object creation?

The __init__ method is the constructor that initializes a newly created object with specific attributes when it is instantiated.



What's Next?

In the next section, you'll dive into inheritance in Python. You'll learn how to create subclasses, reuse code from parent classes, and understand how inheritance supports efficient and modular object-oriented programming.