简体   繁体   中英

How to customise a class to print a string?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM