+ 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
12 odpowiedzi
+ 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__
+ 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.
+ 1
Try : print(personList[0].name)
0
You just have an indent problem of your code inside your class.
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.
0
Try this
personList=personList.append(A)
0
Geoffrey L still not working, it says [<__main__.Person object at 0.7fd4696b8550>]
0
ℂ𝕙𝕚𝕘𝕠𝕫𝕚𝕖 𝔸𝕟𝕪𝕒𝕖𝕛𝕚🇳🇬 says None
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.
0
That worked but its just a name
0
I also removed the .name part and tested but got the same error
0
Lothar it worked,whats __str__ and __repr__ . Are the inbuit like __init__?