简体   繁体   English

Python-程序退出时重置列表,如何将对象存储在列表中以供以后访问?

[英]Python - list reset on program exit, how to store objects in list to access later?

I am new to python trying to write a very simple game with simple login system to save progression later on. 我是python的新手,试图尝试使用简单的登录系统编写一个非常简单的游戏,以便以后保存进度。

I am doing User objects for login and storing in list, but list is empty on program exit, this is what I've written 我正在做用于登录并存储在列表中的用户对象,但是程序退出时列表为空,这就是我写的

class Users(object):


    users = []

    def __init__(self, username=None, password=None):

        global users #recommended from comment on this website other topic

        self.username = username
        self.password = password

#print Users.users[0].username    #was using to check if object saved to list
#print Users.users[0].password

print "L to login, R to register, Q to quit"
answer = raw_input("> ")
if answer == "r":
    username_r = raw_input("Create name: ")
    for user in Users.users:
        if username_r in user.username:
    #if any (self.username == username_r for Users in Users.users):
            print "Name already exists"
    password_r = raw_input("Create password: ")


    u = Users(username_r, password_r)
    Users.users.insert(len(Users.users), u)

    print "\n------------------\n"
    print Users.users[0].username #appends correctly
    print Users.users[0].password

I have tried and read other code from website but it does not store in list permanently to access later on. 我已经尝试从网站上阅读其他代码,但是它不会永久存储在列表中,以后可以访问。

This code is only introduction for game, user opens and he is asked to login or register to start. 该代码仅是游戏的介绍,用户打开后,他会被要求登录或注册以开始。

Using notepad++ and powershell, any help is greatly appreciated, thank you. 使用notepad ++和powershell,非常感谢您的帮助。

I would use Pickle : 我会用Pickle

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. pickle模块实现了一个基本但功能强大的算法,用于对Python对象结构进行序列化和反序列化。 “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. “ Pickling”是将Python对象层次结构转换为字节流的过程,而“ unpickling”是逆运算,从而字节流被转换回对象层次的过程。 Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”. 酸洗(和酸洗)也被称为“序列化”,“编组”或“压平”,但是,为了避免混淆,此处使用的术语是“酸洗”和“酸洗”。

Below is an example for your class Users: 以下是您的班级用户的示例:

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
>>> class Users(object):
...     users = []
...     def __init__(self, username=None, password=None):
...         global users
...         self.username = username
...         self.password = password
... 
>>> import pickle
>>> luke = Users('Luke', 'Skywalker')
>>> messi = Users('Lionel', 'Messi')
>>> 
>>> myusers = [luke, messi]
>>> 
>>> pickle.dump( myusers, open("myusers.p", "wb"))
>>>

So, above i defined the class Users, i made two instances and finally i stored those objects inside a file called myusers.p. 因此,在上面我定义了用户类之后,我创建了两个实例,最后将这些对象存储在名为myusers.p的文件中。 The last step is called to serialize. 最后一步称为序列化。

To recover them you've to do: 要恢复它们,您必须执行以下操作:

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
>>> class Users(object):
...     users = []
...     def __init__(self, username=None, password=None):
...         global users
...         self.username = username
...         self.password = password
... 
>>> import pickle
>>> myusers = pickle.load( open( "myusers.p", "rb" ) )
>>> myusers
[<__main__.Users object at 0x7fe4cecfc350>, 
 <__main__.Users object at 0x7fe4cecfc390>]
>>> myusers[0].username
'Luke'
>>> myusers[1].username
'Lionel'
>>> 

Note that before restoring the objects, the class Users must be defined in current scope. 请注意,在还原对象之前,必须在当前作用域中定义用户类。

If you need go further in this approach you might consider using ZODB , a nosql database or a sql database. 如果需要进一步采用这种方法,则可以考虑使用ZODBnosql数据库或sql数据库。

A good thing of using a pure object storage mechanism like pickle or zodb, is that you deal just with one paradigm, objects. 使用像pickle或zodb这样的纯对象存储机制的一件好事是,您只处理一种范式,即对象。 But in an relational database, you might need to use a object relational mapper (ORM) which adds a little of complexity but if you need to storage big amounts of data and do a lot of queries is one of the best ways to go. 但是在关系数据库中,您可能需要使用对象关系映射器(ORM),这会增加一些复杂性,但是如果需要存储大量数据并执行大量查询,则这是最好的方法之一。 There are plenty of ORMs in Python. Python中有很多ORM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将多个图存储在列表中以便以后访问它们 - store several plots in a list to access them later 如何对股票数据的结构化列表进行排序以便以后在Python中访问? - How to sort a structured list of stock data for later access in Python? 在 python 中,如何在将输入输入列表时退出程序? - In python how to exit the program while taking input into a list? 如何在python中存储(和访问)一个非常大的列表 - How to store (and access) a very large list in python 如何制作 Python 程序,以便即使在终止后,变量、列表和其他对象的值也不会重置? - How can I make a Python program so that even after termination, the variable, list and other objects' values do not reset? 如何访问列表中的特定对象(Python) - How to access specific objects in a list (python) 通过索引访问python列表对象 - Access to python list objects by index 如何读取 python 程序中创建的对象数量并保存为列表 - how to read how many objects created in python program and save as a list 如何将查询返回的两个不同值存储到列表数据类型中以备后用(plpy python) - How to store two different values returned from query into list data types to be used later(plpy python) Python如何在列表中存储电子邮件中解码的unicode字符串,然后在以后使用? - Python How to store decoded unicode string from email in list and then use later?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM