top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Object in Python

Introduction 

Are you prepared to advance your Python knowledge? If so, learning about Python objects and classes is a good way to start. They are the foundation for numerous projects. Learning about objects makes coding much more than just adding numbers or printing strings - it becomes an exercise in making something substantial from separate components.

Read on this Python objects guide to learn what is an Object in Python, the fundamental concepts of objects, the different properties of an object, and how a class is defined and an object is created.

Overview

An object is the core building block of the language, representing real-world entities or abstract concepts. Objects are instances of classes defining their structure and behavior. They encapsulate data as attributes and functionality as methods. Let's understand the objects to model and implement complex systems in Python and create custom data types and functionalities.

What is an Object in Python?

An object is a subclass of a class. It is a set of characteristics (variables) and methods. To do actions, we need a class object. Objects have two distinct characteristics: They have states and behaviors (an object has properties and methods connected to it). Its attributes indicate its state, and its methods represent its behavior. We can modify its state by using its methods.

Each object possesses the following attributes.

  • Identity: Each thing must be individually identifiable.

  • State: An object has an attribute that indicates an object's state and also reflects the property of an object.

  • Behavior: An object has methods that reflect its activity.

Here's an example to illustrate the classes and objects in Python concept:

Example 1

# Define a class called "Person."
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Create two Person objects
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

# Access object attributes and call object methods
print(person1.name)  # Output: "Alice"
person2.greet()      # Output: "Hello, my name is Bob, and I am 25 years old.

Example 2

class Person:
   name=""
   age=0
   city=""
   
   def display(self):
      print("Name: ", self.name)
      print("Age: ", self.age)
      print("City: ", self.city)

# Create the first Person object p1
p1 = Person()
p1.name = "Rahul"
p1.age = 20
p1.city = "Kolkata"

# Call the display method to print p1's attributes
p1.display()

print()

# Create the second Person object p2
p2 = Person()
p2.name = "Karan"
p2.age = 22
p2.city = "Bangalore"

# Call the display method to print p2's attributes
p2.display()

print()

# Call the display method for p1 again
p1.display()

It demonstrates each string object in Python created from the Person class maintains its attribute values, which are independent of other objects. Here's the output based on the code: 

Name: Rahul
Age: 20
City: Kolkata

Name: Karan
Age: 22
City: Bangalore

Name: Rahul
Age: 20
City: Kolkata

As shown in the output, p1 and p2 have their own distinct values for the name, age, and city attributes. When you call the display method for p1 again at the end, it displays the values associated with p1, demonstrating using objects in Python data is independent.

Understanding of Python Object

Understanding using objects in Python and their relationships is fundamental to creating a well-structured, maintainable, and flexible code.  Here are the core concepts of Python class(object) vs class, instances, attributes, and methods. Let's dive deeper to know what is a class in Python with an example:

1. What is a class in Python: 

Classes are blueprints for objects, defining their structure and behavior. Consider a Car class:

Class in Python with an example

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

    def start_engine(self):
        return f"{self.make} {self.model}'s engine started."

2. Instances: 

Instances are individual objects created from a class. You can create multiple car instances with unique attributes:

car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")

3. Attributes: 

Attributes are variables that hold data specific to each instance. In this case, make and model are attributes of car instances:

print(car1.make)  # Output: "Toyota"
print(car2.model)  # Output: "Civic"

4. Methods: 

Methods are functions defined within the class, allowing objects to perform actions. Here, start_engine is a method:

print(car1.start_engine())  # Output: "Toyota Camry's engine started."
print(car2.start_engine())  # Output: "Honda Civic's engine started."

5. Inheritance: 

Python supports inheritance, where one class can inherit attributes and methods from another. For example, you can create an ElectricCar class that inherits from Car:

class ElectricCar(Car):
    def __init__(self, make, model, battery_capacity):
        super().__init__(make, model)
        self.battery_capacity = battery_capacity

    def describe_battery(self):
        return f"{self.make} {self.model} has a {self.battery_capacity} kWh battery."

6. Polymorphism: 

Python supports polymorphism, treating different classes as instances of a common base class. This allows for flexibility in code design and usage:

def get_vehicle_description(vehicle):
    return f"{vehicle.make} {vehicle.model}"

vehicle1 = Car("Ford", "Mustang")
vehicle2 = ElectricCar("Tesla", "Model S", 85)

print(get_vehicle_description(vehicle1))  # Output: "Ford Mustang"
print(get_vehicle_description(vehicle2))  # Output: "Tesla Model S"

7. Constructor (__init__):

The __init__ method initializes object attributes when the object is created. It is called automatically when creating an object.

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

dog1 = Dog("Buddy," "Golden Retriever")

How to Create an Object in Python?

In Python, you can create objects of a class by following these steps:

  • First, create a class. A class is a blueprint or template used to create objects

  • After you've defined a class, use the constructor method to generate objects (instances) of that class. __init__() is the constructor method.

  • After creating an object, you can use dot notation to retrieve its properties (data) and invoke its methods (functions).

Here's an example to illustrate how to create an object in Python in steps:

# Step 1: Define a Class
class Cat:
    # Constructor method
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Method to make the cat meow
    def meow(self):
        print(f"{self.name} say Meow!")

# Step 2: Instantiate Objects
cat1 = Cat("Whiskers", 5)
cat2 = Cat("Fluffy", 3)

# Step 3: Access Attributes and Methods
print(f"{cat1.name} is {cat1.age} years old.")
print(f"{cat2.name} is {cat2.age} years old.")

cat1.meow()
cat2.meow()

Output:

Whiskers is 5 years old.

Fluffy is 3 years old.

Whiskers say Meow!

Fluffy says Meow!

Accessing Class Attributes and Methods:

class Circle:
    pi = 3.14159  # Class attribute

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return self.pi * self.radius**2

# Create an object of the Circle class
circle1 = Circle(5)

# Access class attribute and call class method using the object
print(circle1.pi)       # Access class attribute
print(circle1.area())   # Call class method

Accessing Instance Attributes and Methods:

class Student:
    def __init__(self, name, age):
        self.name = name      # Instance attribute
        self.age = age        # Instance attribute

    def introduce(self):
        return f"My name is {self.name}, and I am {self.age} years old."

# Create an object of Student class
student1 = Student("Alice", 20)

# Access instance attributes and call instance method using the object
print(student1.name)          # Access instance attribute
print(student1.introduce())    # Call instance method

Accessing a Mix of Class and Instance Members:

class Vehicle:
    fuel_type = "Petrol"  # Class attribute

    def __init__(self, make, model):
        self.make = make    # Instance attribute
        self.model = model  # Instance attribute

    def info(self):
        return f"This {self.make} {self.model} runs on {self.fuel_type}."

# Create an object of the Vehicle class
car = Vehicle("Toyota," "Camry")

# Access class attributes, instance attributes, and call an instance method
print(car.fuel_type)   # Access class attribute
print(car.make)        # Access instance attribute
print(car.info())      # Call instance method

SELF Variable

In Python, SELF is a default variable that holds the memory address of the current object. The self-variable can relate to instance variables and methods. When a class object is formed, its object name contains the object's memory address. Because SELF knows the memory address of the object, this memory location is introduced to it internally. Thus, the variable and method of an object are accessible. Because the first parameter to any object method is always an object reference, the first argument is always SELF. Whether you call it or not, this procedure occurs automatically.

Here's an example demonstrating the use of the SELF variable in a class:

class MyClass:
    def __init__(self, value):
        self.value = value  # Instance attribute

    def display(self):
        print(f"The value is: {self.value}")

    def update_value(self, new_value):
        self.value = new_value

# Create an object of MyClass
obj = MyClass(42)

# Access instance attribute and call instance method using the object
obj.display()  # Output: The value is: 42

# Call a method that updates the instance attribute
obj.update_value(100)

# Access the updated instance attribute
obj.display()  # Output: The value is: 100

Modifying Object properties in Python

In Python, you can modify an object's properties (attributes) by using the object's reference and the dot notation to access and update those attributes. Here's how you can do it:

Directly Assign New Values:

You can directly assign new values to an object's attributes using the object reference and dot notation. Here's an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create an object of Person class
person = Person("Alice", 25)

# Modify attributes
person.name = "Bob"
person.age = 30

# Access the modified attributes
print(person.name)  # Output: Bob
print(person.age)   # Output: 30

Using Methods

You can also create methods within the class to update the object's attributes. This is done to encapsulate the logic for updating attributes. Here's a Python classes and objects exercises example:

class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance

    def deposit(self, amount):
        self.balance = amount

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
        else:
            print("Insufficient balance.")

# Create an object of BankAccount class
account = BankAccount("12345", 1000)

# Use methods to deposit and withdraw
account.deposit(500)
account.withdraw(300)

# Access the updated balance
print(account.balance)  # Output: 1200

Deleting an Object in Python

In Python, you can delete an object using the del statement. The del statement removes a reference to an object, allowing the Python garbage collector to reclaim the memory used by the object when there are no more references to it. Here's how you can delete an object:

class MyClass:
    def __init__(self, value):
        self.value = value

# Create an object of MyClass
obj = MyClass(42)

# Delete the object using the 'del' statement
del obj

# Attempting to access 'obj' after deletion will result in an error
# Uncommenting the line below will raise a NameError
# print(obj)

Conclusion

In Python, objects are instances of classes, and they are the building blocks of the language. Objects encapsulate data and behavior to model real-world entities and implement complex systems. Understanding objects and how to work with them is fundamental to Python programming.

FAQs

1: Are objects in Python similar to variables?

Objects and variables are related but different concepts. A variable is a name that references an object in memory. Objects are the actual data structures that hold the values and have associated behavior. 

2: Can I create multiple objects from the same class?

Yes, you can create multiple objects from the same class. Each object is independent and has its own attributes, and can call the class's methods.

3: What is an object () in Python?

The object () is used to construct an object with no features. The object created has all of the methods and attributes used as the foundation for all the classes in the code. 

4: What is an instance variable?

Instance variables are values assigned within the init method (constructor) or method with self.

Leave a Reply

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