0

We had a task in school about classes and i got a mistake in my code...

We had the task to create a class person with some methods like getname, getage and so on. Finally there should be a list with some names. The names should be implemented into the class and finally into the empty list "friends" I wrote this, but obviusly there are some mistakes i don't find. Can you help me, please? :) here is my code: # -*- coding: utf-8 -*- """ Created on Mon Jul 17 13:35:51 2017 @author: Anika """ import random class Person(object): def __init__(self,name): self.name=name self.age=int(random.randint(1,100)) def getname(self): return self.name def getage(self): return self.age def birthday(self): self.age +=1 return self.age def __str__(self): return self.name +' is '+ self.age +' years old.' Names=['Harry','Ron','Hermoine','Ginny','Hedwig'] Friends=[] i=0 while i<len(Names): j=Person(Names[i]) Friends.append(j) print (Friends) i+=1

18th Jul 2017, 10:47 AM
Anika Schmalfeld
Anika Schmalfeld - avatar
3 Answers
+ 3
Hi @Anika, I modified your code a bit, so here it goes: import random class Person(object): def __init__(self,name): self.name=name self.age=int(random.randint(1,100)) def getname(self): return self.name def getage(self): return self.age def birthday(self): self.age +=1 return self.age def __str__(self): return self.name +' is '+ str(self.age)+' years old.' Names=['Dumbledore','Harry','Ron','Hermione','Hagrid','Ginny','Hedwig','Scabbers','Crookshanks'] Friends=[] i=0 while i<len(Names): j=Person(Names[i]) Friends.append(j) print (str(Friends[i])) i+=1
18th Jul 2017, 12:36 PM
Ipang
+ 3
I changed the __str__(self) to use str(self.age) because of type conversion error. And inside the while loop I use print(str(Friends[i])) instead of print(Friends). The str() function invokes the __str__ function from Person class, the __str__ function overrides default str() function, cmiiw. Btw, I see you misspelled Hermione as Hermoine, and I added some other character names just for fun. Hth, Cheers!
18th Jul 2017, 12:46 PM
Ipang
+ 1
:D Thanks a lot!! it works! and Harry is 77 years old ;P
18th Jul 2017, 1:17 PM
Anika Schmalfeld
Anika Schmalfeld - avatar