python - 为什么这不会附加到列表中?

标签 python

所以我正在制作这个程序,您可以在其中向不同的用户发送注释,但是当我尝试这样做时:

这不起作用。 我编写并发送了注释,但是当我以其他用户身份登录时(仍在同一执行中),没有收到注释。

import datetime

#initialise stuff
class Account:
    def __init__(self, un, pw, notes, sent, received):
        self.un = un
        self.pw = pw
        self.notes = notes
        self.received = received
        self.sent = sent

class SentNote:
    def __init__(self, time, note, sender, recipient):
        self.time = time
        self.note = note
        self.sender = sender
        self.recipient = recipient

usernm = ""
passwd = ""
accounts = [Account("Eleeza", "Password", [], [], []), Account("User", "Password", [], [], [])]

signedinas = Account("", "", [], [], [])
#account signing up
def signmenu():
    while True:    
        option = input("Sign [i]n or sign [u]p? >>> ").lower()

        if option == "u":
            signup()
        if option == "i":
            signin()

def signup():
    usernm = input("Make a username >>> ")
    passwd = input("Make a password >>> ")
    accounts.append(Account(usernm, passwd, [], [], []))

def signin():
    inun = input("Username? >>> ")
    inpw = input("Password? >>> ")
    for account in accounts:
        if account.un == inun:
            if account.pw == inpw:
                print("\nSigned in!")
                signedinas.un = account.un
                signedinas.pw = account.pw
                signedinas.notes = account.notes
                appusage()
            else:
                print("Password is incorrect")

def appusage():
    print("Welcome, " + signedinas.un + "!")
    #ask what to do:
    while True:
        print("\nMain Menu\n")
        print("[S]end notes")
        print("[R]eceived notes ({0})".format(len(signedinas.received)))
        print("Sign [O]ut")
        whattodo = input("What would you like to do? >>> ").lower()
            #send note
        if whattodo == "s":
            print("\nSend a note")
            to = input("Username of who you're sending it to? >>> ")
            send = SentNote(datetime.datetime.now(), "", to, signedinas.un)
            print("Write your note:")
            send.note = input("")
            signedinas.sent.append(send)
            for user in accounts:
                if user.un == to:
                    user.received.append(send)
            print("Sent note!")
        if whattodo == "r":
            print("View Received Notes")
            for n in signedinas.received:
                print("From " + n.sender + " at " + str(n.time))
                print(n.note)
                viewoption = input("[N]ext note [B]ack to main menu >>> ").lower()
                if viewoption == "n":
                    continue
                if viewoption == "b":
                    break
        #sign out
        if whattodo == "o":
            print("See you soon!")
            break
signmenu()

最佳答案

signedinas 是一个完全独立的 Account 对象;因此,它不与 accounts 列表中的对象共享信息。

而不是这些行

signedinas.un = account.un
signedinas.pw = account.pw
signedinas.notes = account.notes

您应该只拥有 signedinas = account,然后 signedinas.received 可能会工作得更好。

其次,您将登录同一个帐户 len(accounts) 次,因为您在注销后没有清除输入的内容,因此循环将重复检查例如,之前的 account.un == inun。要解决此问题,应该在 appusage() 调用之后添加一行代码

for account in accounts:
    if account.un == inun and account.pw == inpw:
        print("\nSigned in!")
        signedinas = account
        appusage()
        inun = inpw = None  # Add this

甚至比全局 signedinas 变量更好的是使用参数。例如

def appusage(account):
    print("Welcome, " + account.un + "!")
    print("You have {} received messages.".format(len(account.received))

关于python - 为什么这不会附加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53359697/

相关文章:

python - 使用 django 在 HTML 页面中显示数据库中的数据

python - 检测变量是否为 sympy 类型

python - 正则表达式:匹配单词中未知数量字母的更好方法

python - 是否可以 np.concatenate 内存映射文件?

python - 如何在 scrapy 中获取原始 start_url(在重定向之前)

python - 使用matplotlib设置图例符号不透明度?

python - 《Think Python : How to Think Like a Computer Scientist》》习题9.3有没有更好的算法

python - 无法理解正则表达式,python

python - Pandas 从 str.extractall ('#' 给出错误)

python - 删除python中字符串中数字之间的空格