Objects in Python with Examples

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

An object in Python is a collection of data and methods. Python is an Object-Oriented Programming Language. So, almost everything is an object in Python. Objects represent real-world entities. 

For example, if we want to build a school, we can’t just start immediately building a school. We need a proper plan-a blueprint. First, we create a blueprint, and with the help of that blueprint, we build a school. In Python, school corresponds to an object and blueprint corresponds to a class. 

From the example, we can understand that we need classes to create objects. To create an object school, we need a class. Let’s create the class.

Creating Class in Python

We use the keyword class to create a class. We can understand this clearly in the syntax below.

Syntax of creating class in Object

class ClassName:
    # Statements..

Since we understand the syntax, we can now create a class named Dog.

Example of how to create a class in Python

class Dog:
   def __init__(self,name,age):
      self.name = name
      self.age = age
      self.add_a_dog()
   @classmethod
   def add_a_dog(cls):
       cls.no_of_dogs += 1
   def bark(self):
       return f"{self.name} is barking.."
   def sleep(self):
       return f"{self.name} is sleeping.."
   def birthday(self):
       self.age += 1
       return f"{self.name} is now {self.age} years old"
   no_of_dogs = 0
print(Dog)

Output

<class ‘__main__.Dog’>

In the above code, we have created a class Dog with several attributes and methods and using the class we can create an object dog.

Create an object in Python

To create an object, we use the following syntax

Syntax of how to create Object in Python

object_name = ClassName(arguments)

Using the above syntax, let’s create an object of the class Dog.

Example of creating Object in a Class

dog1 = Dog("Snoopy", 3)
print(dog1)

Output

<__main__.Dog object at 0x105d5b310>

In the above code, we have created an object dog1 of the class Dog

Accessing Object attributes in Python

We can access attributes by using the following syntax:

Syntax

object_name.attribute_name

Example of how to access Python Object Attributes

print(dog1.name)
print(dog1.age)

Output

Snoopy
3

In the above code example, we accessed the object’s name and age attributes.

Unlimited Objects in Python

If we have a blueprint of a car, we can build as many cars as we want using that single blueprint.  Similarly, in Python, we can create as many objects as we want from a single class.

Example of Unlimited Objects in Python

print("Before Creating Objects")
print(f"Number of objects of class Dog = {Dog.no_of_dogs}")
for _ in range(1_000_000):
   Dog("Snoopy", 10)
print(f"After creating objects")
print(f"Number of objects of class Dog = {Dog.no_of_dogs}")

Output

Before Creating Objects
Number of objects of class Dog = 0
After creating objects
Number of objects of class Dog = 1000000

In the above code, we have created a million objects of class Dog. By this, we can understand that Python doesn’t have a limit on the number of objects we can create.

Setting a Limit in Python

If we ever need to set a limit to the number of objects we can create, we can do that using the magic method __new__().

For Example

class Dog:
   def __new__(cls, *args, **kwargs):
       if cls.no_of_dogs >= cls.objects_limit:
           raise RuntimeError(f"Exceeded maximum object limit” >>>   f” {cls.no_of_dogs}")
       instance = object.__new__(cls)
       return instance
   def __init__(self):
       self.add_a_dog()
   @classmethod
   def add_a_dog(cls):
       cls.no_of_dogs += 1
   no_of_dogs = 0
   objects_limit = 3
print("Before Creating Objects")
print(f"Number of objects of class Dog = {Dog.no_of_dogs}")
for _ in range(3):
   Dog()
print(f"After creating objects")
print(f"Number of objects of class Dog = {Dog.no_of_dogs}")
print("Creating the Fourth object")
# Creating the fourth object
Dog()

Output

Before Creating Objects
Number of objects of class Dog = 0
After creating objects
Number of objects of class Dog = 3
Creating the Fourth object
RuntimeError: Exceeded maximum object limit 3

In the above code example, we set the limit to 3 and when we tried to create a fourth object, our program raised a RuntimeError. In this way, we can restrict the number of objects we can create from a class.

Objects Represent Real-World Entities in Python

Objects in Python are similar to real-world objects. Objects have their unique identity, state, and behavior just like real-world objects.

Identity is the name of the object, for example, dog1, snoopy.

For Example

snoopy = Dog("snoopy", 3)
print(snoopy.name)

Output

snoopy

In the above code example, snoopy is the name/identity of the object.

Every object has a unique state and it is provided by creating instance attributes. For example, age and breed.

For Example

print(f"Name of the Dog is {snoopy.name}")
print(f"{snoopy.name} is {snoopy.age} years old")

Output

Name of the Dog is snoopy
snoopy is 3 years old

In the above code example, name and age are the unique attributes of object snoopy.

Behaviour is provided by defining methods. For example, barking and sleeping.

For Example

print(snoopy.bark())
print(snoopy.sleep())

Output

snoopy is barking..
snoopy is sleeping..

In the above code example, barking and sleeping is the behavior of the object snoopy.

The above diagrams illustrate the state, behavior, and identity of an object.

Modifying an Object’s State in Python

We can modify an object’s state by altering the object’s attributes.

We can alter an object’s attributes by using the Python built-in functions.

1. Built-in Functions to Access/Alter Attributes

getattr() setattr()
hasattr() delattr()

2. getattr()

We can access the attribute of an object using this function. It returns the value of the given attribute.

For Example

class Dog:
   name = "Snoopy"
dog1 = Dog()
print(getattr(dog1, 'name'))

Output

Snoopy

3. hasattr() in Python

It returns True if the passed attribute exists, otherwise False.

For Example

print(hasattr(dog1, 'name'))

Output

True

4. setattr() in Python

It is used to modify or create a new attribute. If the passed attribute does not exist, then it creates the passed attribute, otherwise, it just modifies the existing attribute.

For Example

# Modifying an existing attribute
print("Name before", dog1.color)
setattr(dog1, 'name', 'Hachiko')
print("Name after changing", dog1.name)
# Creating a new attribute
setattr(dog1, 'age', 6)
print(f"Age of {dog1.name} is {dog1.age}")

Output

Name before Snoopy
Name after changing Hachiko
Age of Hachiko is 6

5. delattr() in Python

We use this function to delete an attribute. If we try to access it after deleting or if we pass object name instead of class name as its first argument, it raises an AttributeError.

For Example

delattr(Dog, 'age')
print(Dog.age)

Output

AttributeError: type object ‘Dog’ has no attribute ‘age’

Everything is an Object in Python

Since Python is an Object-Oriented programming language, almost everything is an object in Python. The data types, iterables, and almost everything else we see in Python is an object.

1. Data types such as int and float are objects of class int and float respectively. We can see this in the below code

For Example

num1 = 3
num2 = 5.7
print(type(num1), type(num2))
print(isinstance(num1, int), isinstance(num2, float))

Output

<class ‘int’> <class ‘float’>
True True

2. Iterables such as list and type are objects of the class list and class tuple respectively. We can see this in the below code.

For Example

iter1 = [1,2,3]
iter2 = (3,2,1)
print(type(iter1), type(iter2))
print(isinstance(iter1, list), isinstance(iter2, tuple))

Output

<class ‘list’> <class ‘tuple’>
True True

3. We learned that classes create objects but even those classes are also objects. All classes we define are objects of a superclass named object. 

For Example

print(isinstance(Dog, object))

Output

True

We can access the built-in classes, for example, object, int, and float classes,  in the builtins module.

Delete Objects in Python

We can delete objects using the del keyword. Python raises a NameError if we try to access a deleted object.

For Example

dog1 = Dog("Hachiko", 12)  # Creating object
print(f"Before deleting {dog1}")
del dog1  # Deleting object
print(f"After deleting")
print(dog1)  # Trying to access the deleted object

Output

Before deleting <__main__.Dog object at 0x1028038e0>
After deleting
NameError: name ‘dog1’ is not defined

Python raised a NameError when we tried to access the deleted object dog1 in the above code example. 

Object Aliasing in Python

In Python, we can give more than one name to an object. This is called Object Aliasing.

For Example

class Geeks:
   def __init__(self, name):
       self.name = name
website1 = Geeks("PythonGeeks")
website2 = website1
print("Same objects" if website2 == website1 
      else "Different >>> objects")
print("Using name website1: Name of the object is ",         
      website1.name)
print("Using name website2: Name of the object is ", 
       website2.name)

Output

Same objects
Using name website1: Name of the object is  PythonGeeks
Using name website2: Name of the object is  PythonGeeks

In the above code example, we created an object website1 and we assigned the object address to another variable website2 making it another name for our object.

Now both website1 and website2 reference to the same object address and both can be used to access and modify the object. Similarly, we can assign an object address to as many variables as we like thereby giving the object multiple names.

Instances in Python

An instance is a specific object of the class. Let us understand this by using a simple example. 

To create a car, we need a blueprint of the car. We can create as many as we like using the blueprint. Blueprint corresponds to the class. If we created three cars: car1, car2, and car3 using the class, then we can refer to all three cars as objects of the class. To refer to one specific car, let’s say car1, we can use the term instance.

For Example

class Car:
   pass
car1 = Car()
car2 = Car()
car3 = Car()
print(isinstance(car1, Car))

Output

True

In the above code example, we can say car1, car2, car3 are objects of class Car. We can also say car1 is an instance of Car, car2 is an instance of Car and car3 is an instance of Car.

From the example, we can understand that an instance is a single object of a class.

Interview Questions for Objects in Python

Q1. Create an object my_cuboid with height = 10, breadth = 5, and width = 4 and get the volume of the cuboid.

class Cuboid:
   def __init__(self, height, breadth, width):
       self.height = height
       self.breadth = breadth
       self.width = width
   def volume(self):
       return self.height * self.breadth * self.width

Ans 2. Complete code is as follows

my_cuboid = Cuboid(10, 5, 4)
print(my_cuboid.volume())

Output

200

Q2. What is the output of the given code?

class Fish:
   def __init__(self, name):
       self.name = name
   def swim(self):
       return f"{self.name} is swimming"
dora = Fish("Dora")
print(dora.swim())

Ans 2. The output of the given code is

Dora is swimming

Q3. Create a class Worker and initialize with id and wage. Id and wage can be random numbers. The id should be between 1 and 20 whereas wages range from 100 to 1000. Create 20 objects of the class and store them in an iterable. Print the ids of workers whose wage is less than 500 by using instance attributes.

Hint: Random numbers can be generated using the random module

Ans 3. Code is as follows:

import random
class Worker:
   def __init__(self, id, wage):
       self.id = id
       self.wage = wage
workers = []
for i in range(1, 21):
   worker = Worker(i, random.randint(100, 1000))
   workers.append(worker)
   if worker.wage < 500:
       print(worker.id)

Output

2
3
5
8
11
12
13
15

Q4. Create a class Nothing with no body and create an object nothing_again and delete the object. What output we will get if we try to access the deleted object.

Ans 4. Complete code is as follows:

class Nothing:
   pass
nothing_again = Nothing()
del nothing_again
print(nothing_again)

Output

NameError: name ‘nothing_again’ is not defined

Q5. What is the output of the following code?

class City:
   def __init__(self, name):
       self.name = name
city1 = City("New York")
setattr(city1, "name", "Las Vegas")
setattr(city1, "population", 6_35_000)
print(city1.name)
print(city1.population)

Ans 5. The output of the given code is

Las Vegas
635000

Quiz on Objects in Python

Conclusion

In this article, we learned about Python objects. We learned the way to create objects and the number of objects we can create. We discussed the similarities between Python objects and real-world objects and the relationship between instances and objects.

Furthermore, if you have any queries, please feel free to share them with us in the comment section.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google | Facebook


1 Response

  1. Xexus says:

    I believe that in the setattb() example:
    print(“Name before”, dog1.color)
    the second argument should be dog1.name

Leave a Reply

Your email address will not be published. Required fields are marked *