Search code examples
python-3.xuser-input

How do I make my class construction and other functions run once per script run and save user input?


I'm making my first utility Python project that aims to log user input and build on from there.

However, since everything is reset every time I run the script, I cannot save and build my data.

Is this just not possible through scripts and do I have to learn to build a program in order to achieve this?

Here is the cut of my project's code which constructs a class based on user input:

class Investigator:
def __init__(self):
    self.fullname = input("Enter the first and last name of the new investigator: ")
    self.motto = input("Enter the motto: ")
    self.team = [""]
    self.inv_class = {"Survivor":0,"Seeker":0,"Rogue":0,"Guardian":0,"Mystic":0}
    self.fr_inv_class = max(self.inv_class, key=self.inv_class.get) # Retrieves key w/ the highest value from a dictionary.
    self.persist = {"Panache": 0,"Endeavor": 0,"Radiance":0,"Synergy":0,"Inquisitive":0,"Selfless":0,"Tactics":0}
    self.campaign = [""]
    self.camp_count = 0
    self.experience = 0
    self.rank = "Detective"
    
    print("Welcome aboard investigator!")
    self.report()

player1 = Investigator()

There's nothing wrong running this script but I want it to save the data and ignore the "player 1= Investigator()" part after it has already been established so that when I construct more "Investigator" classes such as "player 2=Investigator()", the script only runs the player 2 part which has not been established previously!

I'm not sure if I'm making sense but please help me!

Below is the link to the entire script if you need to take a closer look at:

https://github.com/kke2724/Arkham-Horror-LCG-Investigators--Association/blob/main/Arkham%20Horror%20LCG%20Investigators'%20Association.py

Thank you so much in advance for you programming gods and goddesses!


Solution

  • The easiest is to save the entered data into a file (formats could be json, pickle, or any other one you prefer). Upon loading you check whether such a file is present. If the file is present, you only ask for stuff that is missing:

    import json
    
    
    class Investigator:
    def __init__(self):
        try:
            with open('cache_file.json', 'r') as f:
                parameters = json.load(f)
        except FileNotFoundError:
            parameters = {}
        if 'fullname' not in parameters:
            parameters['fullname'] = input("Enter the first and last name of the new investigator: ")
        self.fullname = parameters['fullname']
        # similar for the rest
        
        print("Welcome aboard investigator!")
        with open('cache_file.json', 'w+') as f:
            json.dump(parameters, f)
        self.report()
    
    player1 = Investigator()
    

    Didn't test the code on my machine, but this should hopefully work. The code will create a json cache file in the working directory of your script.