Python Forum
Help for my assignment - Object Oriented Programming
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help for my assignment - Object Oriented Programming
#1
So for one of my tasks in my assignment, it is required to create a object oriented program with atleast 4 classes and with atleast 1 superclass. We were able to choose whatever programming language that is appropriate to the task in which I chose Python because I have past experience with it. So I asked my lecturer if it was fine to code a virtual vending machine program in which he agreed and I did it, the source code is below however I don't know how to create classes and how to make methods/attributes private or public etc and I know only the basics. So I want the superclass to be "vendingMachine" and the three subclasses to be "Balance", "Items" and "Keypad". If anyone could help that would be greatly appreciated as I am stuck and need to move onto other tasks in the assignment but this is one of the main tasks.

def getBalance():
    balance = 0 #Variable that tracks total amount of coins inserted into the vending machine
    value = [0.10, 0.20, 0.50, 1.00] #List of all the accepted coins that can be inserted into the vending machine               
    return balance, value

def items():
    itemName = ["Water", "Pepsi", "Coke", "Dr Pepper", "Sprite", "Mountain Dew", "Tango Orange", "Tango Cherry"] #These are all the names of every item
    itemPrice = ["0.60", "1.40", "1.50", "1.30", "1.20", "1.10", "1.10", "1.00"] #These are all the prices for each item
    itemCode = ["1a", "1b", "1c", "1d", "1e", "1f", "1g", "1h"] #These are the item codes of all of the items
    
    itemCode[0] = "1a"
    itemCode[1] = "1b"
    itemCode[2] = "1c"
    itemCode[3] = "1d"      #These are the indexed values from the variable itemCode
    itemCode[4] = "1e"
    itemCode[5] = "1f"
    itemCode[6] = "1g"
    itemCode[7] = "1h"
    
    itemPrice[0] = 0.60
    itemPrice[1] = 1.40
    itemPrice[2] = 1.50
    itemPrice[3] = 1.30     #These are the indexed values from the variable itemPrice
    itemPrice[4] = 1.20
    itemPrice[5] = 1.10
    itemPrice[6] = 1.10
    itemPrice[7] = 1.00
    
    return itemCode, itemName, itemPrice, itemCode[0], itemCode[1], itemCode[2], itemCode[3], itemCode[5], itemCode[6], itemCode[7], itemPrice[0], itemPrice[1], itemPrice[2], itemPrice[3], itemPrice[4], itemPrice[5], itemPrice[6], itemPrice[7]
    
def menu():
    itemCode, itemName, itemPrice, itemCode[0], itemCode[1], itemCode[2], itemCode[3], itemCode[5], itemCode[6], itemCode[7], itemPrice[0], itemPrice[1], itemPrice[2], itemPrice[3], itemPrice[4], itemPrice[5], itemPrice[6], itemPrice[7] = items()
    #The line of code above allows this function to use the variables from the function items()
    balance, value = getBalance() #This line of code allows this function to use the variables from the function getBalance()
    print(" ")
    print("============= Vending Machine =============")
    print(itemCode[0], itemName[0], "£{:.2f}".format(itemPrice[0]))
    print(itemCode[1], itemName[1], "£{:.2f}".format(itemPrice[1]))
    print(itemCode[2], itemName[2], "£{:.2f}".format(itemPrice[2]))
    print(itemCode[3], itemName[3], "£{:.2f}".format(itemPrice[3]))     #For each line of the menu where it displays the item code, item name and item price it obtain those values from the list in the items() function
    print(itemCode[4], itemName[4], "£{:.2f}".format(itemPrice[4]))     #This is the menu GUI which displays the different item codes, item names and item price
    print(itemCode[5], itemName[5], "£{:.2f}".format(itemPrice[5]))
    print(itemCode[6], itemName[6], "£{:.2f}".format(itemPrice[6]))
    print(itemCode[7], itemName[7], "£{:.2f}".format(itemPrice[7]))
    print("===========================================")
    print(" ")

def keypad():
    itemCode, itemName, itemPrice, itemCode[0], itemCode[1], itemCode[2], itemCode[3], itemCode[5], itemCode[6], itemCode[7], itemPrice[0], itemPrice[1], itemPrice[2], itemPrice[3], itemPrice[4], itemPrice[5], itemPrice[6], itemPrice[7] = items()
    #The line of code above allows this function to use the variables from the function items()
    balance, value = getBalance() #This line of code allows this function to use the variables from the function getBalance()
    choice = input("Enter the item code of an item you would like to purchase: ") #Asks the user to input the item code of an item they would like to purchase and it is stored in a variable called choice
    if choice == itemCode[0]: #If the variable choice is equal to 1a then...
        print("The price of that item is £{:.2f}".format(itemPrice[0])) #Display the price of Water
        while balance != itemPrice[0]: #While the variable balance is not equal to the price of Water...
            coins = float(input("Insert a coin into the vending machine: ")) #Ask the user to input a coin which is stored in the coins variable
            if coins not in value: #if coins is not in the variable value, which means if it is not in the list of accepted coins then...
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00") #if the user inputs a coin that is not accepted, this message will be displayed
            elif coins in value: #elif coins is not in the variable value, which means if a coin is in the list of accepted coins then...
                balance = coins + balance #Add the value that is stored in the variable coins with the value stored in the variable balance
                print("Balance: £{:.2f}".format(balance)) #Displays the balance once a coin has been inserted
            if balance > itemPrice[0]: #if balance is greater than the price of Water then...
                balance = 0 #Reset the value stored in the variable balance to 0
                print("That is too much money for the price of", itemName[0],"please try again") #Display that the coins inserted is too much money for the price of Water
                print("The price of that item is £{:.2f}".format(itemPrice[0])) #Display the price of Water once the balance has been reset
                print("Balance: £{:.2f}".format(balance)) #Displays the balance once a coin has been inserted
        if balance == itemPrice[0]: #if balance is equal to the price of Water then...
            print("Correct!")
        
    elif choice == itemCode[1]:
        print("The price of that item is £{:.2f}".format(itemPrice[1]))
        while balance != itemPrice[1]: 
            coins = float(input("Insert a coin into the vending machine: "))
            if coins not in value:
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00")
            elif coins in value:
                balance = coins + balance
                print("Balance: £{:.2f}".format(balance))
            if balance > itemPrice[1]:
                balance = 0
                print("That is too much money for the price of", itemName[1],"please try again")
                print("The price of that item is £{:.2f}".format(itemPrice[1]))
                print("Balance: £{:.2f}".format(balance))
        if balance == itemPrice[1]:
            print("Correct!")
        
    elif choice == itemCode[2]:
        print("The price of that item is £{:.2f}".format(itemPrice[2]))
        while balance != itemPrice[2]: 
            coins = float(input("Insert a coin into the vending machine: "))
            if coins not in value:
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00")
            elif coins in value:
                balance = coins + balance
                print("Balance: £{:.2f}".format(balance))
            if balance > itemPrice[2]:
                balance = 0
                print("That is too much money for the price of", itemName[2],"please try again")
                print("The price of that item is £{:.2f}".format(itemPrice[2]))
                print("Balance: £{:.2f}".format(balance))
        if balance == itemPrice[2]:
            print("Correct!")
        
    elif choice == itemCode[3]:
        print("The price of that item is £{:.2f}".format(itemPrice[3]))
        while balance != itemPrice[3]: 
            coins = float(input("Insert a coin into the vending machine: "))
            if coins not in value:
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00")
            elif coins in value:
                balance = coins + balance
                print("Balance: £{:.2f}".format(balance))
            if balance > itemPrice[3]:
                balance = 0
                print("That is too much money for the price of", itemName[3],"please try again")
                print("The price of that item is £{:.2f}".format(itemPrice[3]))
                print("Balance: £{:.2f}".format(balance))
        if balance == itemPrice[3]:
            print("Correct!")
        
    elif choice == itemCode[4]:
        print("The price of that item is £{:.2f}".format(itemPrice[4]))
        while balance != itemPrice[4]: 
            coins = float(input("Insert a coin into the vending machine: "))
            if coins not in value:
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00")
            elif coins in value:
                balance = coins + balance
                print("Balance: £{:.2f}".format(balance))
            if balance > itemPrice[4]:
                balance = 0
                print("That is too much money for the price of", itemName[4],"please try again")
                print("The price of that item is £{:.2f}".format(itemPrice[4]))
                print("Balance: £{:.2f}".format(balance))
        if balance == itemPrice[4]:
            print("Correct!")
        
    elif choice == itemCode[5]:
        print("The price of that item is £{:.2f}".format(itemPrice[5]))
        while balance != itemPrice[5]: 
            coins = float(input("Insert a coin into the vending machine: "))
            if coins not in value:
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00")
            elif coins in value:
                balance = coins + balance
                print("Balance: £{:.2f}".format(balance))
            if balance > itemPrice[5]:
                balance = 0
                print("That is too much money for the price of", itemName[5],"please try again")
                print("The price of that item is £{:.2f}".format(itemPrice[5]))
                print("Balance: £{:.2f}".format(balance))
        if balance == itemPrice[5]:
            print("Correct!")
            
    elif choice == itemCode[6]:
        print("The price of that item is £{:.2f}".format(itemPrice[6]))
        while balance != itemPrice[6]: 
            coins = float(input("Insert a coin into the vending machine: "))
            if coins not in value:
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00")
            elif coins in value:
                balance = coins + balance
                print("Balance: £{:.2f}".format(balance))
            if balance > itemPrice[6]:
                balance = 0
                print("That is too much money for the price of", itemName[6],"please try again")
                print("The price of that item is £{:.2f}".format(itemPrice[6]))
                print("Balance: £{:.2f}".format(balance))
        if balance == itemPrice[6]:
            print("Correct!")
            
    elif choice == itemCode[7]:
        print("The price of that item is £{:.2f}".format(itemPrice[7]))
        while balance != itemPrice[7]: 
            coins = float(input("Insert a coin into the vending machine: "))
            if coins not in value:
                print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00")
            elif coins in value:
                balance = coins + balance
                print("Balance: £{:.2f}".format(balance))
            if balance > itemPrice[7]:
                balance = 0
                print("That is too much money for the price of", itemName[7],"please try again")
                print("The price of that item is £{:.2f}".format(itemPrice[7]))
                print("Balance: £{:.2f}".format(balance))
        if balance == itemPrice[7]:
            print("Correct!")

menu()
keypad()
Reply
#2
To define a class and subclasses, use the class keyword:

class Vending_Machine:
    def __init__(self): # init constructs the class at instantiation
        pass

def Balance(Vending_Machine):
    def __init__(self):
        pass
As for organizing your code, methods can be defined by defining a function indented under the definition of the class (as above). In Python, there is no distinction of public or private when it comes to methods and attributes. The convention is to use a leading underscore for private methods and attributes, but it does nothing in the interpretter.

For your code, I would make the items in items() into attributes under Vending_Machine. They would also be a pair of dicts instead of a trio of lists. By the way, lines 11 through 27 on items() don't really do anything.

Now, subclasses need to make sense in relation to their superclass. Vending_Machine being the superclass of Balance, Items, and Keypad doesn't make sense (e.g. a Keypad is not a vending machine in real life). For what you have, Vending_Machine, Keypad, and Item make sense and the last two make sense as objects stored inside Vending_Machine, not as subclasses though.

Try reorganizing your code under a few classes and we can provide more advice.
Reply
#3
(Jan-05-2019, 02:53 PM)stullis Wrote: To define a class and subclasses, use the class keyword:

class Vending_Machine:
    def __init__(self): # init constructs the class at instantiation
        pass

def Balance(Vending_Machine):
    def __init__(self):
        pass
As for organizing your code, methods can be defined by defining a function indented under the definition of the class (as above). In Python, there is no distinction of public or private when it comes to methods and attributes. The convention is to use a leading underscore for private methods and attributes, but it does nothing in the interpretter.

For your code, I would make the items in items() into attributes under Vending_Machine. They would also be a pair of dicts instead of a trio of lists. By the way, lines 11 through 27 on items() don't really do anything.

Now, subclasses need to make sense in relation to their superclass. Vending_Machine being the superclass of Balance, Items, and Keypad doesn't make sense (e.g. a Keypad is not a vending machine in real life). For what you have, Vending_Machine, Keypad, and Item make sense and the last two make sense as objects stored inside Vending_Machine, not as subclasses though.

Try reorganizing your code under a few classes and we can provide more advice.

When I remove line 11 to 27 in the items() function of the original code, the code doesn't work and here is the error...

[Image: 3218529d8dee53219decf6cc154a3e13.png]
Reply
#4
That's happening because on line 8 the values in the list are strings instead of floats. Remove the quotation marks from each item and it will work again.
Reply
#5
(Jan-05-2019, 03:55 PM)stullis Wrote: That's happening because on line 8 the values in the list are strings instead of floats. Remove the quotation marks from each item and it will work again.

So I got 3 classes, the superclass is vendingMachine and the two subclasses are gui and userChoice. It is fully working a part from I didn't add the other choices yet in which I will, I only have choice "1a" right now but it is working normally. Any improvements I can make and I need to show that I can use inheritance and polymorphism so I need help on those next if you can that will be great!

class vendingMachine:
    itemName = ["Water", "Pepsi", "Coke", "Dr Pepper", "Sprite", "Mountain Dew", "Tango Orange", "Tango Cherry"]
    itemPrice = [0.60, 1.40, 1.50, 1.30, 1.20, 1.10, 1.10, 1.00]
    itemCode = ["1a", "1b", "1c", "1d", "1e", "1f", "1g", "1h"]
    balance = 0  # Variable that tracks total amount of coins inserted into the vending machine
    value = [0.10, 0.20, 0.50, 1.00]  # List of all the accepted coins that can be inserted into the vending machine

class gui(vendingMachine):
    def menu(self):
        print(" ")
        print("============= Vending Machine =============")
        print(vendingMachine.itemCode[0], vendingMachine.itemName[0], "£{:.2f}".format(vendingMachine.itemPrice[0]))
        print(vendingMachine.itemCode[1], vendingMachine.itemName[1], "£{:.2f}".format(vendingMachine.itemPrice[1]))
        print(vendingMachine.itemCode[2], vendingMachine.itemName[2], "£{:.2f}".format(vendingMachine.itemPrice[2]))
        print(vendingMachine.itemCode[3], vendingMachine.itemName[3], "£{:.2f}".format(vendingMachine.itemPrice[3]))     #For each line of the menu where it displays the item code, item name and item price it obtain those values from the list in the items() function
        print(vendingMachine.itemCode[4], vendingMachine.itemName[4], "£{:.2f}".format(vendingMachine.itemPrice[4]))     #This is the menu GUI which displays the different item codes, item names and item price
        print(vendingMachine.itemCode[5], vendingMachine.itemName[5], "£{:.2f}".format(vendingMachine.itemPrice[5]))
        print(vendingMachine.itemCode[6], vendingMachine.itemName[6], "£{:.2f}".format(vendingMachine.itemPrice[6]))
        print(vendingMachine.itemCode[7], vendingMachine.itemName[7], "£{:.2f}".format(vendingMachine.itemPrice[7]))
        print("===========================================")
        print(" ")

class userChoice(gui):
    def choice(self):
        choice = input("Enter the item code of an item you would like to purchase: ") #Asks the user to input the item code of an item they would like to purchase and it is stored in a variable called choice
        if choice == vendingMachine.itemCode[0]: #If the variable choice is equal to 1a then...
            print("The price of that item is £{:.2f}".format(vendingMachine.itemPrice[0])) #Display the price of Water
            while vendingMachine.balance != vendingMachine.itemPrice[0]: #While the variable balance is not equal to the price of Water...
                coins = float(input("Insert a coin into the vending machine: ")) #Ask the user to input a coin which is stored in the coins variable
                if coins not in vendingMachine.value: #if coins is not in the variable value, which means if it is not in the list of accepted coins then...
                    print("The vending machine doesn't accept this coin\nThe vending machine only accepts 0.10, 0.20, 0.50 and 1.00") #if the user inputs a coin that is not accepted, this message will be displayed
                elif coins in vendingMachine.value: #elif coins is not in the variable value, which means if a coin is in the list of accepted coins then...
                    vendingMachine.balance = coins + vendingMachine.balance #Add the value that is stored in the variable coins with the value stored in the variable balance
                    print("Balance: £{:.2f}".format(vendingMachine.balance)) #Displays the balance once a coin has been inserted
                if vendingMachine.balance > vendingMachine.itemPrice[0]: #if balance is greater than the price of Water then...
                    vendingMachine.balance = 0 #Reset the value stored in the variable balance to 0
                    print("That is too much money for the price of", vendingMachine.itemName[0],"please try again") #Display that the coins inserted is too much money for the price of Water
                    print("The price of that item is £{:.2f}".format(vendingMachine.itemPrice[0])) #Display the price of Water once the balance has been reset
                    print("Balance: £{:.2f}".format(vendingMachine.balance)) #Displays the balance once a coin has been inserted
            if vendingMachine.balance == vendingMachine.itemPrice[0]: #if balance is equal to the price of Water then...
                print("Correct!")

vm = vendingMachine()
g1= gui()
u1 = userChoice()
g1.menu()
u1.choice()
Reply
#6
Right now, all of that is "hard coded," meaning that if you wanted to make another vendingMachine, it you would have to code it into another file and do everything by hand. Hard coding should be avoided; programming works with abstractions, after all.

To improve it, we need to abstract a bit. So, vendingMachine contains certain items for sale. A vending machine could have Doritos on Monday, Twix on Tuesday, and Fritos on Wednesday. In other words, the vending machine itself is just a container and we need to be able to replace its contents. To do that, we need a __init__() method that accepts the various lists you have hard coded at the moment. We also need a method to take in new inventory and add it to the current inventory of items and a method to outright replace everything in the vending machine.

By the end of that paragraph, you will be able to do something like this:

vm_soda = vendingMachine(
    ["Water", "Pepsi", "Coke", "Dr Pepper", "Sprite", "Mountain Dew", "Tango Orange", "Tango Cherry"],
    [0.60, 1.40, 1.50, 1.30, 1.20, 1.10, 1.10, 1.00],
    ["1a", "1b", "1c", "1d", "1e", "1f", "1g", "1h"],
    [0.10, 0.20, 0.50, 1.00]
)
vm_snacks = vendingMachine(
    ["Fritos", "Doritos", "Snickers", "Twix"],
    [1.00, 1.00, 1.00, 1.00],
    ["1a", "1b", "1c", "1d"],
    [1.00]
)
Above, we see that we can create vending machines with different inventories and that accept different currency.

Next, sub-classes need to be explained a bit more. So, gui and userChoice are not proper sub-classes of vendingMachine. The problem is that the methods provided by them should really be part of the superclass. As written in your code, you don't need to instantiate each them because each inherits from the previous one (e.i. userChoice.menu() is a valid call as is userChoice.itemName).

Now, examples of good sub-classes would be coffee dispenser, soda/pop vending machine, or gumball machine. Both of those are basically vending machines that are specialized toward something - the coffee dispenser pours hot coffee out of a nozzle, the soda vending machine is refrigerated and lacks a window, and the gumball machine only takes quarters. That's polymorphism. Each has the base functionality of the vending machine plus something specialized.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with writing an objective oriented python assignment mikikiki 5 2,036 Feb-21-2023, 01:18 PM
Last Post: jefsummers
  Verilog HDL Programming to Python Programming? noobcoder 1 3,030 Jul-18-2019, 09:28 PM
Last Post: nilamo
  Object oriented area of a triangle xterakojede 2 8,928 Apr-20-2018, 01:42 PM
Last Post: xterakojede
  Unit 18: Procedural Programming Assignment (Shop Simulation) shaheduk323 28 13,377 Dec-17-2017, 08:31 PM
Last Post: Terafy
  programming assignment mario 2 3,457 Dec-16-2017, 06:28 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020