0

For school we have to create a vending machine and for now i have a very high complexity because I am using many while loops. So I tried to usefunctions.

But now I get weird Errors.

I have this json file:

{
    "Stocki": [
        {
            "product": "Chips",
            "quantity": 10,
            "price": 10
        },
        {
            "product": "Ritter-Sport",
            "quantity": 50,
            "price": 3
        },
        {
            "product": "Salzstangen",
            "quantity": 17,
            "price": 3
        },
        {
            "product": "M&M's",
            "quantity": 3,
            "price": 2
        },
        {
            "product": "Wassermelooooone",
            "quantity": 15,
            "price": 3
        }
    ]
}

This is my Python code:

import os, json

class VendingMachine():
    def __init__(self, vending_machine):
        self.__data_file = os.path.dirname(os.path.abspath(__file__)) + "\\Vending_Machines.json"
        with open(self.__data_file, "r") as f:
            self.__data = json.load(f)

        if vending_machine not in self.__data:
            raise Exception("this Vending Machine does not exist!")

        self.__name = vending_machine
        self.__stock = self.__data[self.__name]

    def __del__(self):
        try:
            self.__data[self.__name] = self.__stock
            print(self.__data[self.__name])
        except:
            pass
        finally:
            try:
                with open(self.__data_file, "w") as f:
                    json.dump(self.__data, f, indent=4)
            except Exception as e:
                print(f"Problem while saving {self.__data_file}")
                print(e)

    def get_stock(self):
        print(f"Stock of {self.__name}:")
        for product in self.__stock:
            print(f'{product["product"]} - Quantity: {product["quantity"]} - Price: {product["price"]}€')

    def get_name(self):
        return self.__name

    def buy_snacks(self, client, snack, quantity):
        for i in self.__stock:
            if(i["product"] == snack):
                new_quantity = i["quantity"] - quantity
                if(new_quantity < 0):
                    raise Exception("We do not have the requested quantity in Stock!")

                price = i["price"] * quantity
                client.withdraw(price)
                i["quantity"] = new_quantity

                return
        
        raise Exception("This Product does not exist!")

if __name__ == "__main__":
    def set_vending():
        try:
            location = input("Enter the Veding-Machine Location: ")
            return VendingMachine(location)
        except Exception as e:
            print(e)
            set_vending()

    vender = set_vending()

    print(vender.get_name())

When I enter the correct Name Stocki, I get this Exception:

Enter the Veding-Machine Location: Stocki
Stocki
[{'product': 'Chips', 'quantity': 10, 'price': 10}, {'product': 'Ritter-Sport', 'quantity': 50, 'price': 3}, {'product': 'Salzstangen', 'quantity': 17, 'price': 3}, {'product': "M&M's", 'quantity': 3, 'price': 2}, {'product': 'Wassermelooooone', 'quantity': 15, 'price': 3}]
Problem while saving "PATH TO JSON-FILE"
name 'open' is not defined

And If enter first something wrong that triggers an Exception and aftewards Stocki it gives me this Error-Message:

Enter the Veding-Machine Location: 123
this Vending Machine does not exist!
Enter the Veding-Machine Location: Stocki
[{'product': 'Chips', 'quantity': 10, 'price': 10}, {'product': 'Ritter-Sport', 'quantity': 50, 'price': 3}, {'product': 'Salzstangen', 'quantity': 17, 'price': 3}, {'product': "M&M's", 'quantity': 3, 'price': 2}, {'product': 'Wassermelooooone', 'quantity': 15, 'price': 3}]
Traceback (most recent call last):
  File "PATH TO PYTHON FILE", line 64, in <module>
    print(vender.get_name())
AttributeError: 'NoneType' object has no attribute 'get_name'

EDIT

Reason for the first Error:

The open function is not defined while interpreter-shutdown. So it is a bad idea to call it in __del__() atexit-Module helped

Muddyblack k
  • 314
  • 3
  • 16
  • 1
    `name 'open' is not defined` I don't see how this error is possible. `open` is a built-in function. Please edit the question and post the full error traceback. – John Gordon Feb 28 '23 at 23:40
  • Yeah that is why I am so confused.... haha It is the complete traceback :/ from: printing ```Exception as e``` – Muddyblack k Feb 28 '23 at 23:44
  • 2
    Either you're on a really weird execution environment, or you're running into the problem that `__del__` is a **really terrible** place to do any sort of actually important work, because by the time it gets invoked, the interpreter might already be busy tearing itself to pieces for interpreter shutdown. `open` really might not be defined if you're in the middle of interpreter shutdown. – user2357112 Feb 28 '23 at 23:51
  • Please note that if there is an exception, Nothing is returned in ```set_vending()``` and ergo ```vender.get_name()``` is invalid because ```vender``` is ```None``` Also, please print out the value of ```self.__data_file``` – ewokx Feb 28 '23 at 23:53
  • 1
    Yes, `__del__` is the problem. It's being called when the environment is (mostly) already destroyed. – John Gordon Feb 28 '23 at 23:55
  • Yes it was indeed the problem. But then there is stille the ``has no attribute`` problem :/ – Muddyblack k Feb 28 '23 at 23:59
  • @ewokx yeah the exception does no return but as long as there is an exception the function gets ``recalled `` until it has a return. At least was that my intension – Muddyblack k Mar 01 '23 at 00:01

0 Answers0