Close Menu
    Trending
    • Implementing DRIFT Search with Neo4j and LlamaIndex
    • Agentic AI in Finance: Opportunities and Challenges for Indonesia
    • Dispatch: Partying at one of Africa’s largest AI gatherings
    • Topp 10 AI-filmer genom tiderna
    • OpenAIs nya webbläsare ChatGPT Atlas
    • Creating AI that matters | MIT News
    • Scaling Recommender Transformers to a Billion Parameters
    • Hidden Gems in NumPy: 7 Functions Every Data Scientist Should Know
    ProfitlyAI
    • Home
    • Latest News
    • AI Technology
    • Latest AI Innovations
    • AI Tools & Technologies
    • Artificial Intelligence
    ProfitlyAI
    Home » Implementing the Coffee Machine Project in Python Using Object Oriented Programming
    Artificial Intelligence

    Implementing the Coffee Machine Project in Python Using Object Oriented Programming

    ProfitlyAIBy ProfitlyAISeptember 15, 2025No Comments10 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Introduction

    is a straightforward hands-on undertaking that enables Python observe on loops, circumstances, and so on. The undertaking is easy; we’ve a espresso machine that has various kinds of espresso a consumer could order, together with the substances which might be required to make them, and their price ticket. A consumer orders a espresso drink, pays in cash, the machine calculates the entire, and if the cost is full, it dispenses the espresso. For a greater understanding of this undertaking, examine my already printed article on In direction of Information Science: Implementing the Coffee Machine in Python

    On this article, we are going to construct the OOP model of the Espresso Machine in Python.

    What’s OOP?

    Object Oriented Programming is a programming idea that’s based mostly on creating Lessons and Objects. In easy phrases, a Class is a template or a blueprint, an outlined broad class, and Objects are the person constructions which might be created from these Lessons. The Class in OOP defines sure options that every one the objects that come from this class may have, these are referred to as the Attributes. Furthermore, the Class additionally outlined sure features that it could possibly do. In OOP terminology, these are referred to as Strategies.

    Suppose we outline a category “Cats”. This can be a broad class and can embrace all sorts of cats as its objects: my cat Figaro, the neighbor’s cat Simba, and so on. Every cat may have some particular person traits like their title, eye coloration, their breed, and so on. These will probably be coded as their attributes. Furthermore, they may also have particular features like having the ability to hunt, sleep, play, meow, and so on. These will probably be coded as their strategies.

    The next is how courses and objects are coded:

    class Cat:
        def __init__(self, title, eye_color, fur_color, breed, age, size):
            self.title = title 
            self.eye_color = age 
            self.fur_color = fur_color
            self.breed = breed
            self.age = age
            self.size = size
      
    
        def hunt(self, animal):
            print(f"My cat {self.title} is searching a {animal}")
    
    
    my_cat = Cat("Figaro", "blue", "black and white", "Persian", "2", "48")
    print(my_cat.title)
    
    neighbour_cat = Cat("Simba", "hazel", "brown", "Siamese", "3", "50")
    neighbour_cat.hunt("mouse")
    Understanding Lessons, Objects, Attributes and Strategies (Picture by Writer)

    We are going to use the above idea and performance to construct an OOP model of a espresso machine.

    Mission Working

    In my earlier article on the Espresso Machine, I completely defined the working of the undertaking. This undertaking will probably be comparable in its working, besides that we’ll make the most of Object-Oriented Programming to attain the identical outcomes. Total, we’ve the next steps:

    Flowchart (Picture by Writer)

    Defining Lessons for our Espresso Machine

    Step one on this undertaking is to outline our courses, one after the other, after which we’re going to use these blueprints to outline objects wanted all through the undertaking.

    Defining the “MenuItem” Class

    To start with we are going to outline the MenuItem class, that may mannequin every merchandise in our menu, and can use the objects created from it within the subsequent class we are going to create Menu.

    class MenuItem:
        def __init__(self, title, water, milk, espresso, value):
            self.title = title
            self.value = value
            self.substances = {
                "water": water,
                "milk": milk,
                "espresso": espresso
            }

    Suppose we need to create an object menuitem of the category MenuItem. In that case, we might want to give it the next parameters: title of the merchandise, the quantity of water required to make this menu merchandise, the quantity of milk required to make this menu merchandise, the quantity of espresso required to make this menu merchandise, and the price of this menu merchandise.

    menuitem object created from the MenuItem Class (Picture by Writer)

    This MeniItem class will probably be used to initialize objects in a while.

    Defining the “Menu” Class

    Subsequent, allow us to outline a category Menu that may comprise the main points of every merchandise that may be ordered. The item menu may be initialized with the constructor beneath, and the menu attribute of this class will probably be an inventory of the three gadgets constructed as objects from the category we constructed earlier MenuItem. We are going to assemble 3 objects from this class with their outlined parameters. So, for instance, the item latte would require 200 ml of water, 150ml of milk, and 24 g of espresso, and the fee will probably be $2.5. All this will probably be modeled inside the category constructor of Menu, which will probably be used to initialize objects of this class. The __init__ methodology is at all times referred to as every time we create an object.

    class Menu:
        def __init__(self):
            self.menu = [
                MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
                MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
                MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
            ]
    

    Now we’ve the Menu attributes, we may also outline two strategies in it. One is to return the names of the obtainable menu gadgets get_items, and the second methodology find_drink, is to seek out the drink that the consumer selects by way of the enter perform.

    class Menu:
    ...
    
        def get_items(self):
            choices = ""
            for merchandise in self.menu:
                choices += f"{merchandise.title}/"
            return choices
    
        def find_drink(self, order_name):
            for merchandise in self.menu:
                if merchandise.title == order_name:
                    return merchandise
            print("Sorry that merchandise shouldn't be obtainable.")

    Creating an Object from the “Menu” Class

    To place this class and its related attributes and strategies to make use of, we are going to first initialize an object menu of the category Menu. We are going to then use the tactic get_items to show to the consumer the gadgets we’ve in our menu.

    menu = Menu()
    drinks = menu.get_items()
    drink_selected = enter(f"Choose your drink {drinks}: ")
    
    menu.find_drink(drink_selected)

    As soon as the consumer has typed their drink, we are going to examine whether it is current within the menu object utilizing the Menu class find_drink methodology. This methodology checks if the consumer enter is current within the menu, it can return that merchandise, in any other case it can print out to the consumer that the drink shouldn’t be obtainable.

    Menu Class strategies (Picture by Writer)

    So if we give an order of a vanilla shake, this system will merely print out that the merchandise shouldn’t be obtainable. When the enter drink is current in our outlined menu, the tactic find_drink will return the merchandise. Now we will use this merchandise in our coding forward.

    Defining the “CoffeeMaker” Class

    Our subsequent step is to outline the CoffeeMaker class. The CoffeeMaker class will retailer the assets specified beforehand, and may have 3 strategies that their objects can be utilized:

    1. report methodology : This methodology will enable the administration to examine the assets within the espresso machine by printing a report of all assets.
    2. is_resources_sufficient methodology: This methodology will examine if the assets within the espresso machine are ample to make the specified drink. It should return True if assets are ample; in any other case will let the consumer know which useful resource is inadequate.
    3. make_coffee methodology: The final methodology will probably be referred to as when this system’s necessities have been fulfilled, and we’ve to make the espresso. This piece of code will deduct the assets and dispense espresso.
    class CoffeeMaker:
        def __init__(self):
            self.assets = {
                "water": 1000,
                "milk": 1000,
                "espresso": 200,
            }
    
        def report(self):
            print(f"Water: {self.assets['water']}ml")
            print(f"Milk: {self.assets['milk']}ml")
            print(f"Espresso: {self.assets['coffee']}g")
    
        def is_resource_sufficient(self, drink):
            can_make = True
            for merchandise in drink.substances:
                if drink.substances[item] > self.assets[item]:
                    print(f"Sorry there's not sufficient {merchandise}.")
                    can_make = False
            return can_make
    
        def make_coffee(self, order):
            for merchandise so as.substances:
                self.assets[item] -= order.substances[item]
            print(f"Right here is your {order.title} ☕️. Take pleasure in!")
    
    

    Defining the “MoneyMachine” Class

    Lastly, allow us to additionally outline the category MoneyMachine. This class will probably be answerable for the cash administration. It should course of cash to examine if cost is made and add the cash obtained to the cash financial institution.

    The MoneyMachine class has the next strategies:

    1. report methodology: This methodology will print how a lot cash we’ve in our account
    2. process_coins methodology: This methodology will course of the cost within the type of cash of nickels, dimes, quarters, and pennies and can calculate the entire.
    3. make_payment methodology : This methodology will probably be used to examine if the cost is made, is it full or if the consumer has overpaid; it can return the change.
    class MoneyMachine:
        CURRENCY = "$"
        COIN_VALUES = {
            "quarters": 0.25,
            "dimes": 0.10,
            "nickles": 0.05,
            "pennies": 0.01
        }
    
        def __init__(self):
            self.revenue = 0
            self.money_received = 0
    
        def report(self):
            print(f"Cash: {self.CURRENCY}{self.revenue}")
    
        def process_coins(self):
            "Please insert cash.")
            for coin in self.COIN_VALUES:
                self.money_received += int(enter(f"What number of {coin}?: ")) * self.COIN_VALUES[coin]
            return self.money_received
    
        def make_payment(self, value):
            self.process_coins()
            if self.money_received >= value:
                change = spherical(self.money_received - value, 2)
                print(f"Right here is {self.CURRENCY}{change} in change.")
                self.revenue += value
                self.money_received = 0
                return True
            else:
                print("Sorry that is not sufficient cash. Cash refunded.")
                self.money_received = 0
                return False
    

    The Ultimate Code

    Now that we’ve outlined our courses, we are going to write the ultimate code that may ask the consumer for his or her order, examine that assets are ample, course of the cash and funds and dispense the drinks when circumstances are happy. All this will probably be achieved by initializing objects.

    money_machine = MoneyMachine()
    coffee_maker = CoffeeMaker()
    menu = Menu()
    
    is_on = True
    
    whereas is_on:
        choices = menu.get_items()
        alternative = enter(f"What would you want {choices}: ")
        if alternative == 'off':
            is_on = False
        elif alternative == 'report':
            coffee_maker.report()
            money_machine.report()
        else:
            drink = menu.find_drink(alternative)
            if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.value):
                coffee_maker.make_coffee(drink)

    In our closing code, we’ve created some time loop that runs constantly except somebody from administration instructions it to cease. We have now achieved this utilizing the is_on boolean variable, which adjustments to False when the administration sorts “off” as enter to the order immediate.

    Furthermore, similar to we did in our espresso machine undertaking with out OOP, we’ve additionally added the report possibility that provides report of all of the assets within the espresso machine, and the cash within the account

    This system will run as follows: It should immediate the consumer to order a drink by displaying the menu gadgets. If the merchandise chosen by the consumer is within the listing, it can first examine if assets are ample, then ask for cost and examine if the cost is full, after which course of the order. All this has been achieved utilizing OOP ideas of courses and objects.

    Conclusion

    Whereas we’ve not totally explored the capabilities of OOP on this undertaking, we’ve efficiently decreased our strains of code by introducing courses and creating objects from them. In terms of extra advanced tasks with quite a few completely different objects, all sharing a standard blueprint, the inclusion of OOP ideas are available far more helpful.

    Nonetheless, this espresso machine undertaking utilizing OOP has been a helpful tutorial to know the fundamentals of Object Oriented Programming. If in case you have any solutions or can consider another movement of duties for this undertaking, be at liberty to share. Until then, take pleasure in your espresso! 😀

    Photograph by Mike Kenneally on Unsplash



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleA Visual Guide to Tuning Gradient Boosted Trees
    Next Article Testa och jämför Google Nano Banana på LMArena mot andra bild-verktyg
    ProfitlyAI
    • Website

    Related Posts

    Artificial Intelligence

    Implementing DRIFT Search with Neo4j and LlamaIndex

    October 22, 2025
    Artificial Intelligence

    Agentic AI in Finance: Opportunities and Challenges for Indonesia

    October 22, 2025
    Artificial Intelligence

    Creating AI that matters | MIT News

    October 21, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Pause Your ML Pipelines for Human Review Using AWS Step Functions + Slack

    May 13, 2025

    Radio Station Slammed for Pretending AI Host Is a Real Person

    April 25, 2025

    No Peeking Ahead: Time-Aware Graph Fraud Detection

    September 14, 2025

    Implementing the Gaussian Challenge in Python

    September 8, 2025

    How To Build Effective Technical Guardrails for AI Applications

    October 6, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    Most Popular

    How to Build Guardrails for Effective Agents

    October 19, 2025

    The Hidden Dangers of Open-Source Data: Rethinking Your AI Training Strategy

    June 10, 2025

    Make Your Data Move: Creating Animations in Python for Science and Machine Learning

    May 6, 2025
    Our Picks

    Implementing DRIFT Search with Neo4j and LlamaIndex

    October 22, 2025

    Agentic AI in Finance: Opportunities and Challenges for Indonesia

    October 22, 2025

    Dispatch: Partying at one of Africa’s largest AI gatherings

    October 22, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 ProfitlyAI All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.