Python - Objects
Why should I learn to solve Python: Objects technical interview questions?
Learn and practise solving Python: Objects technical interview questions and answers to enhance your skills for clearing technical interviews, HR interviews, campus interviews, and placement tests.
Where can I get technical Python: Objects technical interview questions and answers with explanations?
IndiaBIX provides you with lots of fully solved Python: Objects technical interview questions and answers with a short answer description. You can download Python: Objects technical interview questions and answers as PDF files or e-books.
How do I answer Python: Objects technical interview questions from various companies?
You can answer all kinds of Python: Objects technical interview questions by practising the given exercises (short answer type). You can also find the frequently asked Python: Objects technical interview questions with answers from various companies, such as TCS, Wipro, Infosys, CTS, IBM, etc.
In Python, everything is an object. An object is an instance of a class, and a class is a blueprint for creating objects. Objects have attributes and behaviors, which are defined by the class. Let's take a simple example to illustrate the concept of an object in Python:
# Define a simple class named 'Car'
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def display_info(self):
return f"{self.make} {self.model}"
# Create an object (instance) of the 'Car' class
my_car = Car(make="Toyota", model="Corolla")
# Accessing attributes of the object
make_of_car = my_car.make
model_of_car = my_car.model
# Calling a method of the object
info_of_car = my_car.display_info()
In this example, we define a class named 'Car' with a constructor (__init__ method) to initialize the make and model attributes. The class also has a method named 'display_info' to display the information about the car. We then create an object 'my_car' of the 'Car' class with the make as "Toyota" and model as "Corolla". We can access the attributes (make and model) and call the method (display_info) using the object. Let's print the information about the car:
print(f"Make of the car: {make_of_car}")
print(f"Model of the car: {model_of_car}")
print(f"Information about the car: {info_of_car}")
Output:
Make of the car: Toyota Model of the car: Corolla Information about the car: Toyota Corolla
Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of objects. An object is a self-contained unit that consists of both data and methods (functions) that operate on the data. OOP emphasizes the organization of code into reusable and modular components.
There are four main principles of OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism.
1. Encapsulation: Encapsulation involves bundling the data (attributes) and the methods that operate on the data into a single unit known as a class. This helps in hiding the internal details of an object and only exposing what is necessary.
2. Abstraction: Abstraction involves simplifying complex systems by modeling classes based on real-world entities. It allows programmers to focus on the essential features of an object while ignoring unnecessary details.
3. Inheritance: Inheritance allows a class to inherit properties and methods from another class. It promotes code reuse and the creation of a hierarchy of classes.
4. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common base class. It provides flexibility in handling different types of objects through a uniform interface.
Let's illustrate these concepts with a simple Python program:
# Define a base class 'Shape'
class Shape:
def __init__(self, color):
self.color = color
def display_color(self):
return f"Color: {self.color}"
# Define a derived class 'Circle' that inherits from 'Shape'
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def display_area(self):
return f"Area: {3.14 * self.radius ** 2}"
# Define another derived class 'Rectangle' that inherits from 'Shape'
class Rectangle(Shape):
def __init__(self, color, length, width):
super().__init__(color)
self.length = length
self.width = width
def display_area(self):
return f"Area: {self.length * self.width}"
# Create objects of the classes
red_circle = Circle(color="Red", radius=5)
blue_rectangle = Rectangle(color="Blue", length=4, width=6)
# Display information about the objects
info_circle = red_circle.display_color() + ", " + red_circle.display_area()
info_rectangle = blue_rectangle.display_color() + ", " + blue_rectangle.display_area()
In this example, we define a base class 'Shape' with a color attribute. We then create two derived classes, 'Circle' and 'Rectangle', which inherit from the 'Shape' class. Each derived class has its own attributes and methods.
We create objects of the derived classes ('red_circle' and 'blue_rectangle') and display information about them using their respective methods.
Output:
Information about the circle: Color: Red, Area: 78.5 Information about the rectangle: Color: Blue, Area: 24
In Python, both objects and variables are fundamental concepts, but they serve different purposes.
Variable: A variable is a name that refers to a value or an object. It is a way to store and access data in a program. Variables can be of different types, such as integers, floats, strings, etc.
Object: An object is an instance of a class. It is a self-contained unit that consists of both data (attributes) and methods (functions) that operate on the data. Every value in Python is an object, and objects are created from classes.
Let's illustrate the difference between an object and a variable with a simple Python program:
# Define a simple class 'Person'
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create two objects of the 'Person' class
person1 = Person(name="Alice", age=25)
person2 = Person(name="Bob", age=30)
# Assign an object to a variable
variable_person = person1
# Modify the 'name' attribute of 'person1'
person1.name = "Charlie"
# Display information using both the object and the variable
info_object = f"Object: {person1.name}, {person1.age}"
info_variable = f"Variable: {variable_person.name}, {variable_person.age}"
In this example, we define a class 'Person' with 'name' and 'age' attributes. We then create two objects ('person1' and 'person2') of the 'Person' class. Later, we assign the object 'person1' to a variable named 'variable_person'.
When we modify the 'name' attribute of 'person1', it reflects in both the object and the variable since they reference the same instance.
Outputs:
Information using object: Object: Charlie, 25 Information using variable: Variable: Charlie, 25
The key takeaway is that a variable is a reference to an object in Python. Modifying the object through the variable or directly using the object itself will result in the same changes.
In Python, a class serves as a blueprint or template for creating objects. It defines the structure and behavior that the objects will have. The class specifies the attributes (data) and methods (functions) that the objects of that class will possess.
Role of a Class:
- Encapsulates data and methods into a single unit.
- Defines the attributes and behavior that objects will have.
- Provides a blueprint for creating multiple instances (objects) with similar characteristics.
# Define a class named 'Book'
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def display_info(self):
return f"Title: {self.title}, Author: {self.author}"
# Create two objects (instances) of the 'Book' class
book1 = Book(title="Python Programming", author="John Doe")
book2 = Book(title="Data Science Basics", author="Jane Smith")
# Display information about the created objects
info_book1 = book1.display_info()
info_book2 = book2.display_info()
In this example, we define a class 'Book' with an initializer (__init__ method) that sets the 'title' and 'author' attributes. The class also has a method 'display_info' to present information about the book. We then create two objects ('book1' and 'book2') of the 'Book' class. Each object represents a specific book with its own title and author.
Outputs
Information about Book 1: Title: Python Programming, Author: John Doe Information about Book 2: Title: Data Science Basics, Author: Jane Smith
The class 'Book' defines the structure (attributes and methods), and when we create objects based on this class, each object retains its own set of data. This allows for the creation of multiple instances, each with its own characteristics.