无法在pickle中保存对象列表

问题描述 投票:0回答:1

以下是将对象保存到文件中的方法:

def save_to_file(file_path, user):
    # Writing to a file
        try:
            with open(file_path, "rb") as file:
                user_list: list = pickle.load(file)
            user_list.append(user)
            with open(file_path, "wb") as file:
                pickle.dump(
                    [u for u in user_list], file
                )
        except:
            with open(file_path, "wb") as file:
                pickle.dump(
                    [user], file
                )

但是每当我想使用此代码登录时都会失败 第一个保存的对象可以轻松登录 但该文件中的其他对象无法登录

                try:
                    with open(file_path, "rb") as f:
                        user_list: list = pickle.load(f)

                except FileNotFoundError:
                    print("User does not Exists, Register first!")
                    return None
                print(user_list)
                for u in user_list:
                    if str(u.username) == username and str(u.get_password()) == password:
                        print("Login successful...")

这是我打印 user_list 时的输出:

[name : 1, username : 1, phone number : 1, email : No email!, name : 1, username : 1, phone number : 1, email : No email!, name : 2, username : 2, phone number : 2, email : No email!]
__repr__ overrided

这是课程,我使用了 getstate 但我不知道它是否正确 现在我收到此错误:

    user_list: list = pickle.load(f)
                      ^^^^^^^^^^^^^^
TypeError: User.__setstate__() missing 5 required positional arguments: 'username', 'password', 'phone', 'balance', and 'email'
class User:
    """
    This class implements a user model
    that can login and register
    it dumps data to pickle file
    """

    def __init__(
            self, name: str, username: str, password: str, phone: str, balance: int, email: str = None,
    ) -> None:
        self.name: str = name
        self.username: str = username
        self.__password: str = password
        self.phone: str = phone
        self.balance: int = balance
        self.email: str = email

    def get_password(self) -> str:
        return self.__password

    def withdraw(self, amount) -> None:
        # self.balance - amount if self.balance > amount else print('Not Enough Balance Available')
        if self.balance > amount:
            self.balance -= amount
        else:
            print('Not Enough Balance Available')

    def deposit(self, amount) -> None:
        self.balance += amount

    def set_password(self, password) -> None:
        self.__password = password

    def show_balance(self) -> int:
        return self.balance

    def __getstate__(self):
        return self.__dict__
    def __setstate__(self, name,username,password,phone,balance,email):
        self.name: str = name
        self.username: str = username
        self.__password: str = password
        self.phone: str = phone
        self.balance: int = balance
        self.email: str = email
python pickle
1个回答
0
投票

您没有正确定义

__setstate__()
。它接收单个参数,即
__getstate__()
返回的字典,而不是多个参数。

def __setstate(self, d):
    self.__dict__ = d
© www.soinside.com 2019 - 2024. All rights reserved.