1. Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is one of the most important programming paradigms in Python. It provides a structured way to organize code by grouping related data and functionality into reusable units. If you have worked with languages such as Java, C++, or C#, you are probably already familiar with object-oriented programming. Python also supports OOP and provides several features that make working with objects straightforward.
However, before exploring advanced OOP concepts such as inheritance, polymorphism, encapsulation, and abstraction, it is important to understand three fundamental terms:
- Class
- Object
- Reference variable
These three terms form the foundation of object-oriented programming. Once you understand their relationship, the remaining OOP concepts become much easier to learn.
Let’s understand these concepts using some practical, real-world examples before moving to Python code.
2. Understanding Classes and Objects
2.1 What is a Class?
Imagine that you want to construct a large residential building containing 1,000 floors. Can you start constructing the building immediately? Obviously, not. Before construction begins, you need a proper architectural plan. You would approach an architect and ask them to prepare a detailed blueprint of the building.
The blueprint would contain all the necessary information, such as:
- Number of floors in the building.
- Number of rooms on each floor.
- Dimensions of each room.
- Number and positions of doors.
- Number and positions of windows.
- Other structural specifications.
Once the blueprint is ready, construction can begin. Now, suppose you want to construct another building using exactly the same design, but in a different location.
Do you need to prepare another blueprint? No. You can reuse the existing blueprint to construct another building.Similarly, you can construct hundreds of buildings using the same blueprint. This example helps us understand the concept of a class.
A class is a blueprint or template used to create objects. It defines the properties and behaviors that objects created from that class can have. In the building example:
- The architectural blueprint represents a class.
- Each constructed building represents an object.
- Multiple buildings can be constructed using the same blueprint.
3. Formal Definition of a Class
Based on these examples, we can define a class as follows:
A class is a blueprint, template, or design used to create objects. It defines the properties (data) and behaviors (operations) that its objects can have.
A class generally contains two important components:
1. Attributes (Properties)
Attributes represent the data associated with an object. For example, consider a television. Its attributes might include:
- Brand
- Model
- Screen size
- Volume
- Current channel
In Python, attributes are represented using variables.
2. Methods (Behaviors)
Methods represent the operations that an object can perform. For a television, some possible operations are:
- Increase volume.
- Decrease volume.
- Change channel.
- Turn on.
- Turn off.
In Python, methods are functions defined inside a class.
4. What is an Object?
Now that we understand classes, let’s understand the second important term: object. Consider the building example again. An architect prepares a blueprint, and construction workers use that blueprint to construct an actual building. The blueprint itself is not the building. It only describes how the building should be constructed. The actual constructed building has a physical existence. Similarly, in object-oriented programming, an object is an instance of a class.
An object represents an actual entity created using the definition provided by a class.
For example:
- A building constructed using a blueprint is an object.
- A television manufactured using a particular model specification is an object.
- A Ganesh idol created using a mould is an object.
In programming, an object is a runtime entity that has identity, type, and state. An object is an instance of a class. The terms object and instance are commonly used interchangeably when discussing OOP.
4.1 Relationship Between Class and Object
A class and an object are closely related, but they are not the same thing. A class defines the structure and behavior. An object is an individual instance created using that class. For example, suppose we have a class named Car. It defines common properties and behaviors that a car object can have.
We can create multiple objects from this class:
- Car 1: Brand = Toyota, Color = White.
- Car 2: Brand = Honda, Color = Black.
- Car 3: Brand = Hyundai, Color = Red.
All three objects belong to the same class, but each object can maintain its own state. Notice that all three objects are created from the same class. However, they can maintain different attribute values. This is one of the most important characteristics of objects.
4.2 What is a Reference Variable?
We have now understood two important terms:
- Class: A blueprint for creating objects.
- Object: An instance of a class.
Let’s move to the third term: reference variable. Suppose you purchase a Sony television and bring it home. You now have a television, but how will you operate it? You need a remote control.
Using the remote control, you can perform different operations on the television:
- Increase the volume.
- Decrease the volume.
- Change the channel.
- Turn the television on.
- Turn the television off.
The television is the actual object, whereas the remote control provides a way to interact with that object. A reference variable is a variable that refers to an object. Through that variable, we can access the object’s attributes and invoke its methods.
4.4 Multiple Reference Variables for One Object
Suppose you have a television and its remote control gets misplaced. You purchase another remote control. After a few days, you find the old remote as well. Now you have two remote controls for the same television.
Can you operate the television using either remote?
Yes, provided both remotes are compatible and configured correctly. The important point is that both remotes can operate the same television. Similarly, in Python, multiple variables can refer to the same object. An object does not necessarily have only one reference variable. This is an important concept that we will explore through Python code shortly.
5. Implementing Classes and Objects in Python
So far, we have understood the concepts using real-world examples. Let’s now see how Python implements them. Python provides the class keyword to define a class. Consider the following example:
class Car:
pass
Here, we have defined a class named Car. The pass statement is used because we have not added any attributes or methods yet. It allows us to define an empty class without producing a syntax error.
Now, let’s create an object of this class.
class Car:
pass
car1 = Car()
- This creates a class object representing the
Carclass. - The expression
Car()creates a new instance of theCarclass. - The variable
car1refers to the newly created object.
We can create multiple objects from the same class:
class Car:
pass
car1 = Car()
car2 = Car()
car3 = Car()
In this example, three different objects are created using the same class. Each object has its own identity.
6. Understanding Attributes and Methods Through Code
A class becomes more useful when it contains attributes and methods. Let’s extend our Car class.
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def start(self):
print(f"{self.brand} car is starting")
def stop(self):
print(f"{self.brand} car is stopping")
Here, we have introduced two important concepts:
- Attributes:
brandandcolor. - Methods:
start()andstop().
Let’s create objects using this class.
car1 = Car("Toyota", "White")
car2 = Car("Honda", "Black")
Each object maintains its own attribute values. We can access these attributes and invoke methods using the reference variables.
print(car1.brand) print(car1.color) car1.start() car1.stop()
7. Understanding Reference Variables in Python
Now let’s explore reference variables more deeply. Consider the following code:
class Car:
pass
car1 = Car()
car2 = car1
First, Car() creates an object. Next, car1 refers to that object. Finally, the statement car2 = car1 makes car2 refer to the same object. It does not create another object. Both variables refer to the same object.
We can verify this behavior using Python’s is operator.
class Car:
pass
car1 = Car()
car2 = car1
print(car1 is car2)
The is operator checks whether two variables refer to the same object. Since both variables refer to the same object, the result is True.
9. What Happens When an Object Has No References?
Suppose you have a television, but all the remote controls associated with it are lost. The television still physically exists. Losing the remote does not destroy the television. Similarly, in Python, losing one reference variable does not necessarily mean that the object is destroyed.
Consider this example:
class Car:
pass
car1 = Car()
car2 = car1
car1 = None
Initially, both car1 and car2 refer to the same object. After executing car1 = None, the name car1 no longer refers to that object. However, car2 still refers to it. Therefore, the object remains accessible.
Now consider:
car2 = None
At this point, neither car1 nor car2 refers to the original object. If no other references to that object exist, it becomes eligible for garbage collection.
Python has an automatic memory management mechanism that handles the reclamation of objects that are no longer needed. The exact time when memory is reclaimed is determined by Python’s memory management implementation. This is why it is not correct to assume that an object is immediately destroyed as soon as one reference variable is removed.