Home > Software design >  How to customise a class to print a string?
How to customise a class to print a string?

Time:02-01

I am trying to allow a user to create their own record . When I try to print my list this outputs instead:

[<main.user_class object at 0x10dfc3850>]

@AllanWind

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):
            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)

elif choice == "N":
    print("Program Ended.")

else:
    while choice != "Y" and choice != "N":
        print("Invalid choice")
    

CodePudding user response:

This issue is because the print statement is printing the memory address of the object instead of its properties. To print the properties of the object, you can add a str method to the user_class which returns a string representation of the object:

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

#...
print(user_list[0])
  • Related