如何在每个脚本 运行 中创建 class 构造和其他函数 运行 并保存用户输入?

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

我正在制作我的第一个实用程序 Python 项目,旨在记录用户输入并以此为基础进行构建。

但是,由于每次我 运行 脚本时一切都会重置,所以我无法保存和构建我的数据。

这是否无法通过脚本实现?我是否必须学习构建程序才能实现?

这是我的项目代码的剪辑,它根据用户输入构建了一个 class:

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()

这个脚本没有错运行但是我希望它保存数据并在它已经建立之后忽略“player 1= Investigator()”部分,这样当我构建更多“Investigator”时" class例如"player 2=Investigator()",脚本只是运行之前没有建立的player 2部分!

我不确定我是否说得通,但请帮助我!

下面是整个脚本的link,如果您需要仔细查看:

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

在此先感谢编程大神大神们!

最简单的方法是将输入的数据保存到文件中(格式可以是 json、pickle 或您喜欢的任何其他格式)。加载后,您检查是否存在这样的文件。如果文件存在,你只要求缺少的东西:

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()

没有在我的机器上测试代码,但这应该可以工作。该代码将在脚本的工作目录中创建一个 json 缓存文件。