What is an Object? How to Create, Access, Modify and Delete an Object in Python

Learn how to create an object in Python, access the object, modify, and delete it.

Picture of Nsikak Imoh, author of Macsika Blog
The text What is an Object? How to Create, Access, Modify and Delete an Object in Python on a blank image
The text What is an Object? How to Create, Access, Modify and Delete an Object in Python on a blank image

Table of Content

After you have created a class in Python, we will need a way to interact with the class, access it, and modify the attributes.

This is done by creating an instance of the class.

When we create an instance of that class, it is known as the object of the class.

The process of creating an object is called instantiation.

The classes are essentially like a template to create the objects. The object is created using the name of the class.

The object shares all the behavior and attributes of the class, such as the variables and values present in the class.

Attributes may be data or methods. Methods of an object are corresponding functions of that class.

Also, the object inherits the functions mentioned in the class, along with the class's behavior.

In this lesson, you will learn how to create an object in Python, access the object, modify, and delete it.

What is an Object in Python OOP?

An object is simply the instance of a particular class.

Every element in Python is an object of some class, such as the string, dictionary, set, etc.

Objects are different copies of the class with some actual values. We use the object of a class to perform actions.

Objects have two characteristics: They have states and behaviors (an object has attributes and methods attached to it).

Attributes represent its state, and methods represent its behavior. Using its methods, we can modify its state.

Properties of an Object

Before creating an object, we should know that every object has the following properties:

  • State: The state of an object is decided by the attributes of the object i.e., the different items we have in the class, which the object inherits. Attributes may be data or methods.
  • Behavior: The behavior is represented by the methods of the object. It shows the difference and similarities of the functionality of an object to other objects.
  • Identity: Every object must be uniquely identified. We can make this by giving it a unique name like obj1, obj2, obj3, etc.

How to Create an object in Python

When you create an object from a class. The constructor of that class automatically runs first.

A constructor is a special method used to create and initialize an object of a class.

This method is defined in the class.

A single class can have multiple objects.

The instantiating of an object in Python is divided into two parts: Object Creation and Object initialization.

Internally, the __new__ is the method that creates the object.

The __init__() method allows us to implement a constructor to initialize the object.

Here is the syntax for creating an object of a particular class:

[object_name] = [class_name](arguments)
  
Highlighted code sample.

Here, the object_name is like the car models, namely, Volvo, Tesla, etc.

The class_name is similar to the car blueprint, i.e. the name of the class itself.

The arguments are just like the car's features, which can pass to some particular car models (objects).

We will be using the example of the class we created in the previous tutorial for our demo:

class Car:
    # class variable
    speed_measurement = "KM/hr"
  
      def __init__(self, model, brand, color):
          # data members (instance variables)
          self.model = model
          self.brand = brand
          self.color = color
  
      # Behavior (instance methods)
      def info(self):
          print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
  
    # class method
      @classmethod
      def set_speed_measurement(cls, new_measurement):
          # modify class variable
          cls.speed_measurement = new_measurement
          return None
  
  # create object of a class
  tesla = Car("Y", "Tesla", "Black")
  tesla.info()
  
  # create another object of a class
  toyota = Car("Corolla", "Toyota", "Gold")
  toyota.info()
  
  # Output
  # Model: Y Brand: Tesla Color: Black
  # Model: Corolla Brand: Toyota Color: Gold
  
Highlighted code sample.

In the above example, tesla is a unique instance of the class Car and toyota is also a unique instance of the class car.

They are both objects and both embody the properties of an object by having a unique identity, a state, and behavior that are unique to each.

How to Access the Attributes of an Object in Python

An instance attribute can be accessed or modified by using the dot notation:

instance_name.attribute_name
  
Highlighted code sample.

Objects do not share instance attributes.

Instead, every object has its copy of the instance attribute and is unique to each object.

However, unlike instance variables, the value of a class variable is the same from object to object.

All instances of a class share the class variables.

Only one copy of the static variable will be created and shared between all objects of the class.

Let's take an example.

class Car:
    # class variable
    speed_measurement = "KM/hr"
  
      def __init__(self, model, brand, color):
          # data members (instance variables)
          self.model = model
          self.brand = brand
          self.color = color
  
      # Behavior (instance methods)
      def info(self):
          print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
  
    # class method
      @classmethod
      def set_speed_measurement(cls, new_measurement):
          # modify class variable
          cls.speed_measurement = new_measurement
          return None
  
    # class method
      @classmethod
      def get_speed_measurement(cls):
          # get class variable
          print(cls.speed_measurement)
  
  # Instance of tesla accessing instance methods and variable
  tesla = Car("Y", "Tesla", "Black")
  tesla.info()
  
  # Instance of toyota accessing instance methods and variable
  toyota = Car("Corolla", "Toyota", "Gold")
  toyota.info()
  
  # Output
  # Model: Y Brand: Tesla Color: Black
  # Model: Corolla Brand: Toyota Color: Gold
  
  
Highlighted code sample.

How to Access the Class Attributes of an Object in Python

From the example above, when we access the instance attribute with the objects, we get unique outputs.

However, when we call the class attribute, we get the same value.

This is a result of what we mentioned earlier that each object has its copy of the instance attribute that is unique to each object while the value of a class variable is the same from object to object.

A class variable is accessed using the class name.

Here is the syntax for accessing a class attribute — Take note of the absence of brackets.

ClassName.attribute_name
  
Highlighted code sample.

This syntax above is not the same as:

ClassName().attribute_name
  
Highlighted code sample.

For example, this is how you would call a class attribute:

# Access the class attribute
  Car.get_speed_measurement()
  
Highlighted code sample.

Output:

# KM/hr
  
Highlighted code sample.

The code syntax below will give you a TypeError for missing parameters because it assumes you want to instantiate the class.

# Access the class attribute
  Car().get_speed_measurement()
  
Highlighted code sample.

Output:

TypeError: Car.__init__() missing 3 required positional arguments: 'model', 'brand', and 'color'
  
Highlighted code sample.

And doing this:

Car("Y", "Tesla", "Black").get_speed_measurement()
  # or
  Car("Y", "Tesla", "Black").speed_measurement
  
Highlighted code sample.

Will not give you an error.

However, it's the same as simply accessing the class attribute through an instance:

 tesla.get_speed_measurement()
   toyota.get_speed_measurement()
  
Highlighted code sample.

The static method also works similarly to the class method.

# Access static attributes
  print(tesla.get_region())
  print(toyota.get_region())
  print(Car.get_region())
  
Highlighted code sample.

Output:

# West Africa
  # West Africa
  # West Africa
  
Highlighted code sample.

In the above code snippet, we have created a class named Car, and using the object, along with the dot(.) operator, we accessed the values of the attributes.

How to Modify the Attributes of an Object in Python

Once we declare objects, we can modify their properties and values.

Every object has properties associated with them.

We can set or modify the object's properties after object initialization by calling the property directly using the dot operator.

The modification of an object is done using dot notation.

Obj.PROPERTY = new_value
  
Highlighted code sample.

Let's take an example to understand how this works.

Supposedly, we no longer want to deal in Toyota Corolla and Tesla model Y.

We can change the model by calling that property and assigning it a new model.

class Car:
    # class variable
    speed_measurement = "KM/hr"
  
      def __init__(self, model, brand, color):
          # data members (instance variables)
          self.model = model
          self.brand = brand
          self.color = color
  
      # Behavior (instance methods)
      def info(self):
          print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
  
    # class method
      @classmethod
      def set_speed_measurement(cls, new_measurement):
          # modify class variable
          cls.speed_measurement = new_measurement
          return None
  
    # class method
      @classmethod
      def get_speed_measurement(cls):
          # get class variable
          print(cls.speed_measurement)
  
  # Instance of tesla accessing instance methods and variable
  tesla = Car("Y", "Tesla", "Black")
  tesla.info()
  
  # Instance of toyota accessing instance methods and variable
  toyota = Car("Corolla", "Toyota", "Gold")
  toyota.info()
  
  # Change the Car models
  tesla.model = "X"
  toyota.model = "Camry"
  
  tesla.info()
  toyota.info()
  
  # Output
  # Model: Y Brand: Tesla Color: Black
  # Model: Corolla Brand: Toyota Color: Gold
  
  # Model: X Brand: Tesla Color: Black
  # Model: Camry Brand: Toyota Color: Gold
  
Highlighted code sample.

Here in the above code snippet, we set the value for the model of the tesla object to “X” and the value of the model of the Toyota to “Camry”.

When you access the value again by calling the info() method, you will notice the updated information.

How to Modify Class Attributes in Python

How do you modify the variables of a class?

You simply call the name of the class with the dot notation, followed by the name of the attribute.

ClassName.attribute_name = new_value
  
Highlighted code sample.

From our example, assuming we want to change the speed measurement from “KM/hr” to “M/s”.

It will be:

Car.Car.speed_measurement = "M/s"
  Car.get_speed_measurement()
  
Highlighted code sample.

NOTE: You cannot modify a class attribute through the instance.

For example, if you run the code below without initially explicitly modifying it by Car.get_speed_measurement(),

tesla.speed_measurement = "D/t"
  tesla.get_speed_measurement()
  Car.get_speed_measurement()
  
Highlighted code sample.

This will be your output:

KM/hr
  KM/hr
  KM/hr
  
Highlighted code sample.

To modify the class variable with the instance, do it with the class method.

For example:

tesla.set_speed_measurement("M/r")
  tesla.get_speed_measurement()
  Car.get_speed_measurement()
  
Highlighted code sample.

The code above will modify the class variable.

How to Delete the Attributes of an Object in Python

There is a way to delete an object which was created earlier in the code by using the del keyword.

Continuing with the previous example of the Car class, here we delete the “model” property from the “tesla” object.

del tesla.model
  
Highlighted code sample.

After deleting the object of a class, the name of the object which is bound to it gets deleted.

However, the object continues to exist in the memory with no name assigned to it.

Later it is automatically destroyed by a process known as garbage collection.

Also, be careful with what you delete as deleting an attribute without proper exception handling will cause errors in your program.

For example, accessing the deleted attribute through the code:

tesla.model
  # or
  tesla.info()
  
Highlighted code sample.

This will lead to the error below:

AttributeError: 'Car' object has no attribute 'model'
  
Highlighted code sample.

How to Delete Class Attributes in Python

To delete a class variable, call the del statement with the class followed by the dot notation and the attribute.

For example:

del Car.speed_measurement
  
Highlighted code sample.

Again, be careful with what you delete as deleting an attribute without proper exception handling will cause errors in your program.

Note: You cannot delete a class variable using the instance of the class.

For instance, the code below will not make any difference.

del tesla.speed_measurement
  
Highlighted code sample.

Wrap Off

In this lesson, you learned about the Objects in Python, which is a concept of OOPs.

Objects and Classes are quite important concepts in Python.

Many of the popular software are based on this concept of OOPs.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.

Next Tutorial — What are Constructors in Python And How to use Them in OOPGet the Complete Code of Object Oriented Programming in Python on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?