尝试在使用文件访问时更改对象中的某些值

问题描述

我正在尝试更改对象的特定部分。具体来说,我试图从 acc 中减去某个值。然后将更改记录在已创建的文本文件中。

Traceback (most recent call last):
  File "main.py",line 152,in <module>
    start()
  File "main.py",line 141,in start
    withdraw(id,input("How much do you want to withdraw?"))
  File "main.py",line 55,in withdraw
    if allCustom[d].hkid== x:
TypeError: list indices must be integers or slices,not Customer
class Customer: 
    def __init__(self,name,date,address,hkid,acc):
        self.name = name
        self.date = date
        self.address = address
        self.hkid = hkid
        self.acc = acc
allCustom = [customer1,customer2,customer3,customer4,customer5]
customer1 = Customer ("Sarah Parker","1/1/2000","Hong Kong,Tai Koo,Tai Koo Shing Block 22,Floor 10,Flat 1","X1343434","2222")
def withdraw (x,y):
    global allCustom
    count = 0
    for d in allCustom:
        if allCustom[d].hkid== x:
            if int(allCustom[d].acc) >= int(y):
                allCustom[d] = Customer (allCustom[d].name,allCustom[d].date,allCustom[d].address,allCustom[d].hkid,str(int(allCustom[d].acc)-int(y)))
                print("Success! Please collect your money.")
                break
            else:
                print("Sorry but you have inseffecient funds to withdraw $"+y)
        elif count == len(allCustom):
            print("Your HKID does not match any account in our database. Returning to starting screen")
        else:
            count +=1
def UpdateFile():
    global allCustom
    OutFile=open("CustomInfo.txt","w")
    for c in allCustom:
      OutFile.write(f"\nName:{c.name}\n")
      OutFile.write(f"Birth Date:{c.date}\n")
      OutFile.write(f"Address:{c.address}\n")
      OutFile.write(f"HKID:{c.hkid}\n")
      OutFile.write(f"Account value:{c.acc}\n")
    OutFile.close()
UpdateFile()

解决方法

正如@furas 在评论中所说,只需使用:

if d.hkid== x:

这是因为 for d in allCustom:迭代列表 allCustom 将变量 d 绑定到列表中的每个项目转动。此时 d 是一个 Customer 对象,您可以访问它的属性。因此,您无需尝试在列表中查找客户,因为您已经在 d 中引用了该客户。

您需要更正其余代码中的其他 allCustom[d] 实例。


你可能因为这个 Python 习语而感到困惑:

for i in range(len(allCustom)):
    if allCustom[i].hkid== x:

使用索引来访问列表中的项目。首选第一种形式 for d in allCustom - 它更清晰、更简洁。