Search code examples
pythonarrayslistrecord

An attribute error appeared when I tried to make a code allowing a user to create their own record


I am trying to allow a user to create their own record and output their record. When I run my code this message appears:

File "filename", line 25, in record = user_class(fact_list) File "filename", line 17, in init self.feild_list[i]=feild_list[i] AttributeError: 'user_class' object has no attribute 'feild_list'

This is my code:

user_list = []

choice=input("Enter choice (Y/N):")

if choice == "Y":
    feild_list = []

    record_length = int(input("Enter record length:"))

    for i in range(record_length):
        feild = input("Enter a feild:")
        feild_list.append(feild)

    class user_class():
        def __init__(self, feild_list):
            for i in range(record_length):
                self.feild_list[i]=feild_list[i]

    fact_list = []

    for i in range(len(feild_list)):
        fact = input("Enter a fact:")
        fact_list.append(fact)
    
    record = user_class(fact_list)

    user_list.append(record)
    print(user_list)

    choice=input("Enter choice (Y/N):") 
        
elif choice == "N":
    print("Program Ended.")

else:
    while choice != "Y" or choice != "N":
        print("Invalid choice")
        choice = input("Enter choice (Y/N):")

Solution

  • In user_class.__init__() you don't have a self.feild_list variable. I assume you want one (see below). Alternatively you could just clone the list self.feild_list = feild_list[:].

    user_list = []
    
    choice = input("Enter choice (Y/N):")
    
    if choice == "Y":
        feild_list = []
    
        record_length = int(input("Enter record length:"))
    
        for i in range(record_length):
            feild = input("Enter a feild:")
            feild_list.append(feild)
    
        class user_class():
            def __init__(self, feild_list):
                self.feild_list = []
                for i in range(record_length):
                    self.feild_list.append(feild_list[i])
    
        fact_list = []
    
        for i in range(len(feild_list)):
            fact = input("Enter a fact:")
            fact_list.append(fact)
    
        record = user_class(fact_list)
    
        user_list.append(record)
        print(user_list)
    
        choice = input("Enter choice (Y/N):")
    elif choice == "N":
        print("Program Ended.")
    
    else:
        while choice != "Y" and choice != "N":
            print("Invalid choice")
            choice = input("Enter choice (Y/N):")
    

    Also fixed the logic error in the choice retry. Consider moving that retry logic to the start so always get a valid choice:

    while True:
        choice = input("Enter choice (Y/N):")
        if choice in "NY":
            break
        print("Invalid choice")