Published Aug. 3, 2023, 11:02 a.m.
Programming paradigms play a significant role in how we design and structure our code. Two common paradigms are procedural programming and object-oriented programming (OOP). Let's explore their characteristics and differences:
Procedural programming follows a sequential approach, where a list of instructions is executed step by step.
Characteristics:
Examples of Procedural Languages:
Object-oriented programming is an approach to problem-solving where computation is organized using objects.
Characteristics:
Examples of Object-Oriented Programming Languages:
Python is a versatile object-oriented programming language. In Python, everything is an object, including classes, objects, functions, methods, and modules. These objects can be passed as arguments to functions or assigned to variables.
Object-Oriented Programming System (OOPS) adheres to several principles, which define its core concepts:
In Python, a class is a blueprint or plan to create objects. A class allows us to define the properties (attributes) and actions (behaviors) of an object.
How to Define a Class:
A class in Python is defined using the class
keyword, followed by the class name and a colon. The class body contains instance variables, static and local variables, as well as instance methods, static methods, and class methods.
class ClassName:
'''documentation string'''
variables: instance variables, static and local variables
methods: instance methods, static methods, class methods
The documentation string represents a description of the class and is optional. We can retrieve the doc string using two methods:
print(className.__doc__)
help(className)
Let's create a Car
class that represents the properties and actions of a car object.
class Car:
'''This class represents a car object'''
# Instance Variables
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# Instance Method
def start(self):
return f"{self.make} {self.model} is starting."
# Instance Method
def stop(self):
return f"{self.make} {self.model} has stopped."
# Creating Car Objects
car1 = Car("Toyota", "Corolla", 2022)
car2 = Car("Honda", "Civic", 2023)
# Accessing Properties and Methods
print(car1.make) # Output: Toyota
print(car2.model) # Output: Civic
print(car1.start()) # Output: Toyota Corolla is starting.
print(car2.stop()) # Output: Honda Civic has stopped.
Now, let's create a MathOperations
class that performs basic arithmetic operations.
class MathOperations:
'''This class performs basic arithmetic operations'''
# Static Method
@staticmethod
def add(a, b):
return a + b
# Static Method
@staticmethod
def subtract(a, b):
return a - b
# Class Method
@classmethod
def multiply(cls, a, b):
return a * b
# Using Static and Class Methods
result1 = MathOperations.add(5, 3) # Output: 8
result2 = MathOperations.subtract(10, 4) # Output: 6
result3 = MathOperations.multiply(2, 6) # Output: 12
print(result1, result2, result3)
In this example, the Car
class has instance variables (make, model, and year) and instance methods (start() and stop()). Output: 8 6 12
An object is a fundamental concept in object-oriented programming. It can be defined as a collection of data and its associated functionality. In simpler terms, an object represents a real-world entity that possesses both states (properties) and behaviors (functionalities).
Properties of an Object: The properties of an object refer to its state. There are two types of properties:
Behaviors of an Object: The behaviors of an object refer to its functionalities. Similar to properties, there are two types of behaviors:
Let's consider two examples of objects to better understand the concept:
Object1: Human
Object2: Animal
Identity: Each object is uniquely identified by an identity, which can be considered as the name of the object.
State: Every object has properties that define its state. The state of an object can only be modified by invoking its behaviors.
Behavior: Behaviors refer to the functionalities (methods) associated with the object. Only behaviors can alter the state of the object.
In object-oriented programming, classes act as blueprints for creating objects. Objects are instances of classes, containing specific data and functionality defined in the class. The class provides a template, and the objects are the concrete instances created based on that template.
class ClassName:
def __init__(self, arg1, arg2, ...):
# Initialize instance variables here
def method1(self, arg1, arg2, ...):
# Define method behavior here
# Create an object
obj_name = ClassName(arg1_value, arg2_value, ...)
Let's create a simple Car
class and instantiate an object to represent a car. We'll set some properties (attributes) for the car and implement a method (behavior) to display its information.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
return f"Car: {self.make} {self.model} ({self.year})"
# Create a Car object
car1 = Car("Toyota", "Corolla", 2022)
# Display Car information using the method
print(car1.display_info())
Output:
Car: Toyota Corolla (2022)
In this example, we defined a Car
class with an __init__
method to initialize the instance variables (make
, model
, and year
). We also created a display_info
method to showcase the car's details. We then created a car1
object using the class constructor and passed the necessary arguments. Finally, we printed the information about the car using the display_info
method, which displayed the output as Car: Toyota Corolla (2022)
.
In Python, a reference variable is a variable that refers to an object in memory. Instead of directly storing the object itself, the reference variable holds the memory address where the object is located. It acts like a pointer or a link to the object.
Let's consider an example to understand reference variables:
# Define a simple class called Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create two Person objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# Assign person1 to person3
person3 = person1
# Modify the age of person1
person1.age = 26
# Display information of all persons
print("Person 1:", person1.name, person1.age) # Output: Person 1: Alice 26
print("Person 2:", person2.name, person2.age) # Output: Person 2: Bob 30
print("Person 3:", person3.name, person3.age) # Output: Person 3: Alice 26
Explanation:
In this example, we define a simple Person
class with an __init__
method to initialize the name
and age
attributes. We create two Person
objects, person1
with the name "Alice" and age 25, and person2
with the name "Bob" and age 30.
Next, we assign person1
to person3
using the =
assignment operator. This means that both person1
and person3
now reference the same object in memory. They share the same data.
When we modify the age
attribute of person1
to 26, it also affects the age
attribute of person3
, because both variables point to the same object.
Finally, we display the information of all three persons using the print
statements. We can observe that person1
and person3
have the same age, which confirms that they are referencing the same object in memory. person2
, on the other hand, is not affected by the changes made to person1
, as it references a different object. This behavior exemplifies the concept of reference variables in Python.