Spark Tech & AI - Comprehensive Information on Python, Python Libraries and Artificial Intelligence and Machine Learning. Full stack Development with JavaScript Frameworks like React, AngularJS, Blogging and Digital marketing, SEO Optimisitation, Artificial Intelligence Chatbots and Agents
Message passing is a way to request a unit of code engage in a behaviour, i.e. changing its state, or sharing some aspect of its state.
Consider the real-world analogue of a letter sent via the postal service. Such a message consists of: an address the message needs to be sent to, a return address, the message itself (the letter), and any data that needs to accompany the letter (the enclosures). A specific letter might be a wedding invitation. The message includes the details of the wedding (the host, the location, the time), The recipient should (per custom) send a response to the host addressed to the return address letting them know if they will be attending.
In Python Object-Oriented Programming (OOP) Message passing refers to the process of objects interacting with one another by calling methods (or functions) on each other. It is a core concept in OOP, where objects send and receive messages, which are essentially method calls. In Python, when you invoke a method on an object, you are passing a "message" to that object, asking it to perform an action or return a value.
Key Points:
1. Objects as Receivers of Messages: Objects encapsulate data (attributes) and behaviour (methods). When one object calls a method of another object, it sends a message to that object.
2. Methods as Handlers of Messages: Methods define how an object responds to a specific message. The method’s implementation processes the message and performs the desired action.
3. Dynamic Behaviour: Message passing allows objects to interact in a dynamic way. The exact method that gets called depends on the object receiving the message, supporting polymorphism.
Example:
Let’s look at a simple example where different objects respond to a common message:
The `make_animal_speak` function sends the "speak" message to the `dog` and `cat` objects.
Each object has a different implementation of the `speak` method.
The behaviour (the returned sound) changes depending on the object that receives the message.
Advantages:
Encapsulation: Objects encapsulate behaviour, and message passing allows them to interact without exposing their internal states.
Polymorphism: Different objects can respond to the same message in different ways, leading to flexible code.
Abstraction: Message passing hides the details of how an object handles a particular request, promoting abstraction.
Message passing is thus a core concept in object-oriented design that allows different objects to work together while maintaining clean, modular code. Now let us discuss the key points with numerous examples on each point to clear the concept of Message passing in Python Object Oriented Programming.
Objects as Receivers of Messages
Here are some examples of Objects as receivers of messages.
1. Bank Account Example
In this example, a BankAccount object encapsulates data like balance and behaviour like depositing or withdrawing money. The object receives messages when methods are called on it, and it responds by performing the action (deposit/withdrawal).
def pause(self): if self.is_playing: self.is_playing = False return"Music paused" return"No music playing"
def stop(self): if self.is_playing: self.is_playing = False return"Music stopped" return"No music playing"
# Object instance
player = MusicPlayer()
# Sending messages
print(player.play("Song A")) # Start playing (message) print(player.pause()) # Pause music (message) print(player.stop()) # Stop music (message) Explanation: player.play("Song A") sends a"play" message tothe player object, asking itto play a song. player.pause() sends a"pause" message, causing the object to pause the current music. player.stop() sends a"stop" message, instructing the player tostopthe music.
5. E-commerce Cart Example
In an e-commerce application, a ShoppingCart object encapsulates a list of items and provides behaviours like adding or removing items.
cart.add_item("Laptop") sends an "add_item" message to the cart object, asking it to add a laptop to the cart.
cart.remove_item("Phone") sends a "remove_item" message, which causes the cart to remove the specified item.
cart.view_cart() sends a "view_cart" message to display the current contents of the shopping cart.
In each example, the object encapsulates its own data (attributes) and behaviors (methods). When you call a method on an object, you're sending a message to that object, asking it to perform an action based on its internal state. This interaction is a fundamental concept of OOP in Python, enabling objects to communicate in a modular, flexible way.
Methods as Handlers of Messages:
1. Vending Machine Example
A `VendingMachine` object has methods to handle user actions such as inserting coins, selecting items, and dispensing the product. Each method processes a specific message.
Method `insert_coin()’ handles the message of inserting a coin by updating the balance.
Method `select_product()`processes the message of product selection by checking if enough balance exists and dispensing the product.
Method `refund()`responds by returning the remaining balance to the user.
2. ATM Machine Example
An `ATM` object has methods to handle operations like checking balance, depositing, and withdrawing money. Each method responds to user messages (requests).
Method `deposit()` handles the deposit message by increasing the balance.
Method `withdraw()` processes the withdrawal request and adjusts the balance if sufficient funds exist.
Method `check_balance()` responds by showing the current balance.
3. Thermostat Example
A `Thermostat` object controls room temperature and responds to messages like setting the temperature, increasing or decreasing it, and showing the current temperature.
classThermostat: def__init__(self, temperature=20): self.temperature = temperature
defset_temperature(self, new_temp): self.temperature = new_temp return f"Temperature set to {self.temperature}°C."
defincrease_temperature(self, increment): self.temperature += increment return f"Increased temperature to {self.temperature}°C."
defdecrease_temperature(self, decrement): self.temperature -= decrement return f"Decreased temperature to {self.temperature}°C."
defshow_temperature(self): return f"Current temperature is {self.temperature}°C."
Object instance thermostat = Thermostat()
Sending messages and methods responding print(thermostat.set_temperature(22)) # Set temperature (message) print(thermostat.increase_temperature(3)) # Increase temperature (message) print(thermostat.decrease_temperature(2)) # Decrease temperature (message) print(thermostat.show_temperature()) # Show current temperature (message)
Explanation:
Method `set_temperature()` handles the message of setting a specific temperature.
Method `increase_temperature()` responds by increasing the temperature by a
specified value.
Method `decrease_temperature()` processes the message by reducing the temperature.
Method `show_temperature()` responds by showing the current temperature.
4. Library System Example
In this example, a `Library` object has methods to handle checking out, returning, and searching for books.
defcheck_out(self, book): if book in self.books and self.books[book] > 0: self.books[book] -= 1 returnf"Checked out {book}. Remaining copies: {self.books[book]}" elif book notin self.books: returnf"{book} is not available in the library." else: returnf"{book} is out of stock."
defreturn_book(self, book): if book in self.books: self.books[book] += 1 returnf"Returned {book}. Available copies: {self.books[book]}" returnf"{book} does not belong to this library."
defsearch_book(self, book): if book in self.books: returnf"{book} is available with {self.books[book]} copies." returnf"{book} is not available."
Object instance
library = Library()
Sending messages and methods responding print(library.check_out("Python 101")) # Check out a book (message) print(library.return_book("Python 101")) # Return a book (message)
print(library.search_book("AI Basics")) # Search for a book (message)
Explanation:
Method `check_out()`responds to the message by reducing the number of available copies of a book.
Method `return_book()` processes the return message and increases the number of available copies.
Method `search_book()` handles the search message by providing information about book availability.
5. Online Order System Example
An `Order` object represents an online order system where methods handle actions like adding products, removing them, and calculating the total.
classOrder: def__init__(self): self.items = {}
defadd_item(self, item, price): if item inself.items: self.items[item] += 1 else: self.items[item] = 1 return f"Added {item} to cart. Total {self.items[item]}."
defremove_item(self, item): if item inself.items: ifself.items[item] > 1: self.items[item] -= 1 else: del self.items[item] return f"Removed {item} from cart." return f"{item} not in cart."
deftotal_price(self): return f"Total price: ${sum(self.items[item] * price for item, price in self.items.items())}"
Object instance order = Order()
Sending messages and methods responding print(order.add_item("Laptop", 800)) # Add item to order (message) print(order.add_item("Mouse", 50)) # Add another item (message) print(order.remove_item("Mouse")) # Remove item from order (message) print(order.total_price()) # Get total price (message)
Explanation:
Method `add_item()` handles the message of adding an item to the order.
Method `remove_item()` responds to the message by removing an item from the cart.
Method `total_price()` processes the message by calculating the total price of the items in the cart.
In each of these examples, methods act as handlers that process incoming messages (method calls) and perform specific actions. The object receives the message, and the corresponding method interprets it to update the state, perform calculations, or return a response. This encapsulation of logic and response to messages is central to the behaviour of objects in Python's Object-Oriented Programming (OOP).
Dynamic behaviour and polymorphism through message passing in Python.
Each example demonstrates how different objects can respond to the same message in different ways, depending on the object receiving the message.
1. Animal Sound Example (Polymorphism)
In this example, different animal objects respond to the same "speak" message differently based on their type.
classAnimal: defspeak(self): raise NotImplementedError("Subclass must implement abstract method")
The same message, speak(), is passed to different objects (Dog, Cat, Cow).
Each object has its own version of the speak() method, so the response depends on the object receiving the message.
This demonstrates polymorphism, where the exact method that gets called depends on the object's type.
2. Shape Area Example (Polymorphism)
In this example, different shape objects (circle, rectangle, square) respond to the same message "area" and return different calculations based on their shape.
classShape: defarea(self): raise NotImplementedError("Subclass must implement abstract method")
The message render() is passed to different document objects (PDF, Word, HTML).
Each document type responds in its own way based on its format, demonstrating dynamic behaviour and polymorphism.
5. Vehicle Fuel Example (Polymorphism)
In this example, different vehicle types (car, bike, and truck) respond to the same "fuel_consumption" message differently based on the type of vehicle.
classVehicle: deffuel_consumption(self): raise NotImplementedError("Subclass must implement abstract method")
classCar(Vehicle): deffuel_consumption(self): return"Car consumes 8 liters per 100 km."
classBike(Vehicle): deffuel_consumption(self): return"Bike consumes 3 liters per 100 km."
classTruck(Vehicle): deffuel_consumption(self): return"Truck consumes 15 liters per 100 km."
print(calculate_fuel(car)) # Outputs: Car consumes 8 liters per 100 km. print(calculate_fuel(bike))# Outputs: Bike consumes 3 liters per 100 km. print(calculate_fuel(truck))# Outputs: Truck consumes 15 liters per 100 km.
Explanation:
The message fuel_consumption() is passed to different vehicle objects (Car, Bike, Truck).
Each vehicle type responds with its specific fuel consumption rate, illustrating dynamic behaviour and polymorphism
In each example, different objects respond to the same message in a way that's specific to their type, demonstrating polymorphism. This dynamic behaviour allows objects of different types to be treated uniformly (e.g., by calling the same method), while still responding in a way that suits their internal implementation. This is a fundamental feature of object-oriented programming and is essential for writing flexible and scalable code.
No comments:
Post a Comment