+ 1

How to append this A person to personList and print it out?

I made a list and tried to append the A to it. But when i print it out i get error.ignore the comments. https://code.sololearn.com/cQ12uB95UV97/?ref=app

24th Feb 2022, 4:15 PM
Lenoname
12 Answers
+ 5
Lenoname , why not trying this: class Person: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def __str__(self): return f"{self.name}, {self.age}, {self.sex}" def __repr__(self): return f"{self.name}, {self.age}, {self.sex}" #Initialize an instance of the object: A = Person("John", 34, "Male") personList = [] print(A) # this uses __str___ personList.append(A) print(personList) # this uses __repr__
24th Feb 2022, 4:56 PM
Lothar
Lothar - avatar
+ 5
Lenoname , this is an explanation from the official python documentation: object.__repr__(self): called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. object.__str__(self): called by the str() build-in function and by the print statement to compute the "informal" string representation of an object.
24th Feb 2022, 5:28 PM
Lothar
Lothar - avatar
+ 1
Try : print(personList[0].name)
24th Feb 2022, 4:41 PM
Geoffrey L
Geoffrey L - avatar
0
You just have an indent problem of your code inside your class.
24th Feb 2022, 4:19 PM
Geoffrey L
Geoffrey L - avatar
0
class Person: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex #Initialize an instance of the object: A = Person("John", 34, "Male") personList = [] personList.append(A) print(personList) Just edited the tab before "def __init__" and then pushed each rows, then it's fine.
24th Feb 2022, 4:19 PM
Geoffrey L
Geoffrey L - avatar
0
Try this personList=personList.append(A)
24th Feb 2022, 4:25 PM
Chigozie Anyaeji 🇳🇬
Chigozie Anyaeji 🇳🇬 - avatar
0
Geoffrey L still not working, it says [<__main__.Person object at 0.7fd4696b8550>]
24th Feb 2022, 4:29 PM
Lenoname
0
It works : [<__main__.Person object at 0.7fd4696b8550>] is a normal output, it says that you are printing an Person object inside a list type.
24th Feb 2022, 4:41 PM
Geoffrey L
Geoffrey L - avatar
0
That worked but its just a name
24th Feb 2022, 4:49 PM
Lenoname
0
I also removed the .name part and tested but got the same error
24th Feb 2022, 4:51 PM
Lenoname
0
Lothar it worked,whats __str__ and __repr__ . Are the inbuit like __init__?
24th Feb 2022, 5:10 PM
Lenoname