Lesson 50 of 70 – Python Objects
71%

Python Objects

An object is an instance of a class. Objects are one of the most important concepts in Object Oriented Programming (OOP). An object can contain data, called attributes, and behavior, provided by methods.

Note: In Python, almost everything is an object, including numbers, strings, lists, functions, and classes.

What is an Object?

An object is a specific instance created from a class. The class defines the structure, while the object contains actual data.

class Student:

    name = "Rahul"


student1 = Student()

Here, Student is the class and student1 is an object of that class.

Creating an Object

An object is created by calling the class name followed by parentheses.

class Student:

    pass


student1 = Student()

print(student1)

The output will show a representation containing the class name and the object's identity information.

Object Attributes

Object attributes store information belonging to a particular object. They are commonly created using self.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student1 = Student("Rahul", 20)

print(student1.name)
print(student1.age)

Output:

Rahul
20

Objects Can Have Different Data

Multiple objects created from the same class can contain different data.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student1 = Student("Rahul", 20)

student2 = Student("Amit", 22)

print(student1.name)
print(student2.name)

Output:

Rahul
Amit

Object Methods

Methods are functions defined inside a class. They can operate on the data of an object.

class Student:

    def __init__(self, name):

        self.name = name


    def display(self):

        print("Student:", self.name)


student1 = Student("Rahul")

student1.display()

Output:

Student: Rahul

The self Parameter

The self parameter refers to the current object. It allows instance methods to access attributes and other methods belonging to that object.

class Student:

    def __init__(self, name):

        self.name = name


    def show(self):

        print(self.name)


student = Student("Rahul")

student.show()

Output:

Rahul

Object State

The state of an object is represented by the values stored in its attributes.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student = Student("Rahul", 20)

print(student.name)
print(student.age)

Here, the object's state includes the student's name and age.

Changing Object Data

Object attributes can be changed after an object has been created.

class Student:

    def __init__(self, name):

        self.name = name


student = Student("Rahul")

print(student.name)

student.name = "Amit"

print(student.name)

Output:

Rahul
Amit

Adding an Attribute

Python allows an attribute to be added directly to an individual object.

class Student:

    pass


student = Student()

student.name = "Rahul"
student.age = 20

print(student.name)
print(student.age)

Output:

Rahul
20

Deleting an Object Attribute

The del keyword can be used to delete an attribute from an object.

class Student:

    def __init__(self):

        self.name = "Rahul"
        self.age = 20


student = Student()

del student.age

print(student.name)

Output:

Rahul

Object Identity

Every object has an identity. The built-in id() function can be used to obtain an integer representing the object's identity during its lifetime.

class Student:

    pass


student = Student()

print(id(student))

The exact number depends on the running Python process and may be different each time the program runs.

Checking the Type of an Object

The type() function tells us the type or class of an object.

class Student:

    pass


student = Student()

print(type(student))

Output will be similar to:

<class '__main__.Student'>

Using isinstance()

The isinstance() function checks whether an object is an instance of a specified class. It returns True or False.

class Student:

    pass


student = Student()

print(isinstance(student, Student))

Output:

True

Comparing Objects with is

The is operator checks whether two references refer to the same object.

class Student:

    pass


student1 = Student()

student2 = student1

print(student1 is student2)

Output:

True

Here, both variables refer to the same object.

Two Different Objects

class Student:

    pass


student1 = Student()

student2 = Student()

print(student1 is student2)

Output:

False

Although both objects are created from the same class, they are different objects.

The __dict__ Attribute

For many normal Python objects, the __dict__ attribute contains the object's instance attributes.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student = Student("Rahul", 20)

print(student.__dict__)

Output:

{'name': 'Rahul', 'age': 20}

Object Representation with __str__()

The __str__() method can define a user-friendly string representation of an object.

class Student:

    def __init__(self, name):

        self.name = name


    def __str__(self):

        return self.name


student = Student("Rahul")

print(student)

Output:

Rahul

Object Representation with __repr__()

The __repr__() method can provide an unambiguous representation of an object and is commonly used when displaying or debugging objects.

class Student:

    def __init__(self, name):

        self.name = name


    def __repr__(self):

        return f"Student({self.name!r})"


student = Student("Rahul")

print(repr(student))

Output:

Student('Rahul')

Calling Multiple Object Methods

class Calculator:

    def add(self, a, b):

        return a + b


    def multiply(self, a, b):

        return a * b


calculator = Calculator()

print(calculator.add(10, 20))

print(calculator.multiply(5, 4))

Output:

30
20

Passing an Object to a Function

Objects can be passed to functions just like other Python values.

class Student:

    def __init__(self, name):

        self.name = name


def display_student(student):

    print(student.name)


student = Student("Rahul")

display_student(student)

Output:

Rahul

Returning an Object from a Function

A function can also create and return an object.

class Student:

    def __init__(self, name):

        self.name = name


def create_student():

    return Student("Rahul")


student = create_student()

print(student.name)

Output:

Rahul

Class vs Object

Class Object
Blueprint or template Instance of a class
Defines attributes and methods Contains actual object data
Created using class keyword Created by calling the class
Can create many objects Represents a particular instance

Real-World Example

Suppose we are developing a school management system. We can create a Student class and then create many student objects.

class Student:

    def __init__(self, name, course):

        self.name = name
        self.course = course


student1 = Student(
    "Rahul",
    "Python"
)

student2 = Student(
    "Amit",
    "Java"
)

print(student1.name)
print(student1.course)

print(student2.name)
print(student2.course)

Output:

Rahul
Python
Amit
Java

Object Lifecycle

A simplified object lifecycle can be understood as:

  1. Define a class.
  2. Create an object from the class.
  3. Initialize the object's data.
  4. Use the object's attributes and methods.
  5. Remove references to the object when it is no longer needed.
class Student:

    def __init__(self, name):

        self.name = name


student = Student("Rahul")

print(student.name)

del student

Key Points

  • An object is an instance of a class.
  • Objects can contain attributes and methods.
  • The __init__() method is commonly used to initialize objects.
  • The self parameter refers to the current object.
  • Different objects created from the same class can contain different data.
  • The type() function checks the type of an object.
  • The isinstance() function checks whether an object belongs to a class.
  • The id() function returns an identity value for an object during its lifetime.
  • The is operator checks object identity.
  • Objects can be passed to functions and returned from functions.
  • __str__() can provide a user-friendly string representation.
  • __repr__() can provide a useful representation for debugging.

🧠 Quick Quiz

Question: What is an object in Python?