Object in Python | Create, Example

We know that Python is an object-oriented programming language that allows us to design our code through classes and objects. In accordance with the concepts of OOPs, a class is a template or blueprint of an object. It provides the state and behaviour of an object.

In Python, almost everything is an object with its properties and methods. For example, strings, functions, lists, dictionaries, files, etc. are considered objects in Python.

An object is a basic unit of an object-oriented programming language. An entity that has state and behavior is called object in Python or other object-oriented programming languages.

Here, the state represents properties, and behavior represents actions or functionality. Hence, objects in Python consist of states or attributes (called data members) and behaviors (called functions). An object is a runtime instance of a defined class. Each instance of an object holds its own relevant data or value.

In Python, an object can refer to anything that can have a name, such as functions, integers, strings, floats, classes, methods, and modules. It is a collection of data, and methods utilize that data.

Objects are flexible in nature that we can use them in different ways. We can assign them to variables, dictionaries, lists, tuples, or sets. We can pass them as arguments.

Characteristics of Object in Python


An object in Python or any other programming languages has three characteristics:

1. State: The specific data held in an object’s member variables is called state of the object. It is also called properties or attributes of the object. It is typically represented by variables. During the execution of a program, the state of an object may change frequently.

2. Behavior: The behavior represents functionality or actions that an object can perform. It is usually represented by functions (or methods) within a class. Methods are used to change the state of an object.

3. Identity: The identity represents the unique name of an object. It differentiates one object from the other. The unique name of an object is used to identify the object.

Let’s understand these characteristics of an object with the help of real-time examples.

Realtime Example of Objects in Python


An object can refer to anything in the real world that has properties and actions or behaviors. For example, person, book, pen, pencil, TV, fridge, washing machine, mobile phone, etc.

Realtime Example 1:

Let’s take a real-time example “person” as an object. An object “person” has three characteristics: identity (name), state (properties), and behavior (actions). Look at the below figure.


Realtime example of object in Python

From the above figure, it is clear that a person is an object. The first property of the person (object) is black hair, which we can represent in Python like this:

hairColor = "black" # Here, black is the state of an object.

In the same way, the second property of the object is eye color, which we can represent it in Python like this:

eyeColor = "black"

Similarly, we can represent other properties of the object like this. These properties of a person are called attributes (also called instance data).

Let’s consider the behaviors or actions of a person. The behaviors of a person may be eat, sleep, walk, play, and study. We represent these behaviors in Python like this: eat(), sleep(), walk(), play(), and study(). These are called functions or methods.

Thus, when properties and behaviors are combined together of any real-world object, make an object in Python.

Nouns in English represent properties or states of an object. We can represent it with the help of variables, whereas verbs represent actions/behaviors, which we can represent with the help of functions.


Realtime Example 2:

Let’s take one more interesting example, “Mobile”. If I tell you to represent this phone in Python as an object, then How will you do like that?

You can do that very easily. Ask two questions: What it has? (i.e. Properties) and What it does? (i.e. Actions)
There are the following properties of a mobile phone. They are:

  • width = “6.2 inches”
  • height = “13.6 cm”
  • color = “black”
  • OS = “Android”
  • price = “$1000”
  • brand = “Google”
  • weight = “130 gm”

The actions or behaviours of a mobile phone in the terms of Python functions are as:

  • call()
  • sendSms()
  • runApp()
  • browserInternet()
  • sharing()

Realtime Example 3:

Another real-time example we can take “Pencil”. A pencil is an object. Its name is Natraj.

  • State: color is black.
  • Behavior: It is used to write. So, writing is behavior.

Thus, you can take any object around you and think about what property it has? And what action it does?

How to Create Object in Python?


To create an object of a class in Python, we first need to define a class of its type. A class is a blueprint for creating objects. Once a class is defined, we can create instances of that class, which are called objects.


The process of creating an instance object of a specific class is called instantiation. Creating an instance of a class is very simple. We just need to call the class using class name and pass in whatever argument values to the attributes defined in the __init__() methods. We can create multiple objects of a single class.

The general syntax to create an object of a class in Python is as:

obj_name = class_name(value1, value2, . . .)

In the above syntax, obj_name represents a reference variable that refers to an object. This reference variable contains the memory address that points to an object stored in the heap memory. value1, value2, . . . are the argument values to be supplied to the data members of the class through constructor (i.e. __init__() method).

Let’s take some examples in which we will create multiple objects for a class Student.

# Create the first object of class Student.
st1 = Student()

# Create the second object of class Student.
st2 = Student("Mahika", 15)

In the above example, we have created two objects, st1 and st2. When we have created st1, we have passed no argument value. While creating the second object st2, we have passed two values.

Class Declaration and Object Creation Example


Let’s take some simple example in which we will define a class and create instances of that class by passing none or multiple argument values to the attributes defined in the __init__() methods.

Example 1:

class Person:
    def __init__(self):
        print("I am person.")

# Create the first object of class person without passing any value to its __init__() method.
p1 = Person()

# Create the second object of class person without passing any value to its __init__() method.
p2 = Person()
Output:
       I am person.
       I am person.

In this example, we have created a class named Person in which we have defined __init__(self) method. This method is basically a constructor of the class that will call when the object of the class is created. Inside the constructor, we have defined a print statement.

Then, we have created two objects of the class Person. When the interpreter will execute these statements, it will call constructor method and display “I am Person” on the console two times.

Python automatically puts the first parameter self in the method header, that refers to the current object of the class. The function of self is to connect the method with the object of a class and allow us to access data attributes and methods stored in objects.


Note: For all methods defined inside a class, the first parameter is always “self”, which refers to the object itself. It is used to refer to the data attributes and methods of object.

How to Access Object Attributes in Python?


In Python, we can access attributes and methods defined in the class by using dot (.) operator, as in Java or C++. The general syntax to access attributes or methods is as follows:

obj_name.attributeName
obj_name.methodName()

For example:
   st1.name # accessing class variable or class attribute.
   st1.age  # accessing class variable.
   st1.displayInfo() # accessing a class method.

Let’s take some example programs based on accessing attributes and methods defined inside the class.

Example 2:

class Employee:
    def __init__(self, name, age, salary):
    # Object attributes and method parameters.
        self.name = name
        self.age = age
        self.salary = salary

    def display_emp(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Salary: ", self.salary)

# Create the first object of class by passing arguments to its class constructor.
emp1 = Employee("John", 24, 50000)

# Call the method using reference variable emp1.
emp1.display_emp()

print()

# Create the second object of class by passing arguments to its class constructor.
emp2 = Employee("Bob", 25, 60000)

# Call the method using reference variable emp2.
emp2.display_emp()
Output:
       Name: John
       Age: 24
       Salary: 50000

       Name: Bob
       Age: 25
       Salary: 60000

In this example code, we have defined a class named Employee that contains a class constructor __init__() and display_emp() method. The constructor method __init__() initializes the values to attributes name, age, and salary when we will create an object of the class. We have defined display_emp() method to display the employee’s information.

Let’s understand each statement one by one.

1. def __init__(self, name, age, salary):

  • The __init__() is a special function that initializes the instance of the class. It is a constructor of the class. When we create an object of the class in Python, the interpreter will automatically look for __init__() method. So, we just have to define it, but we do not need to call it explicitly.
  • This constructor method __init__() contains four arguments: self, name, age, and salary. The values of these arguments will assign through the constructor method.
  • The first argument of this function is self that connects the method to the instance of class. The self argument is mandatory in Python for every function (method) to be defined inside the class.
  • The argument values that follow the “self” are the parameters of method.
  • Once the method has connected to the object, the values of method parameters are passed on to the object attributes.
  • Inside the __init__() method, on the left side of “=” sign, we have object attributes and on the right-hand side, we have the method parameters.
  • By convention, we use the same name for both object attributes and method parameters.

2. Object creation:

  • We have created two objects of class Employee by passing two different argument values. When the interpreter executes the statement emp1 = Employee(“John”, 24, 50000), it will automatically call the class constructor and pass argument values to its parameters of the class constructor.
  • Now, in the __init__() method, the argument values passed to the method parameters are assigned to the object attributes as follows:
    • self.name = “John”
    • self.age = 24
    • self.salary = 50000

3. Calling method:

  • To display the values of object emp1, we have defined a method named display_emp.
  • The display_epm() method has only an argument “self” which gives it access to the object (which is in our case emp1).
  • When we will call the display_emp() method using reference variable emp1, the argument self provides the access to emp1. Then, it prints the values of all object attributes on the console. The same procedure happens for the second object’s creation.

Example 3:

class Animal:
    def sound(self):
        print("I am a dog and I sound bhow bhow.")
    def leg(self):
        print("I have four legs.")

# Create an instance of class.
ani = Animal()

# Call both the functions using reference variable ani.
ani.sound()
ani.leg()
Output:
       I am a dog and I sound bhow bhow.
       I have four legs.

Example 4:

class Test:
    def __init__(self, x = 1, y = 2):
        print(x + y)

# Create multiple objects of the class Test by passing different arguments.
t = Test()
t2 = Test(5)
t3 = Test(4, 6)
Output:
       3
       7
       10

In this tutorial, we have explained object in Python with real-time examples. Hope that you will have understood the basic concept of creating objects in Python and practiced all example programs. In the next, we will understand what is constructor in Python and how to create it with the help of examples.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love