+ 2
Why is this not working?
I tried to put petlist[0] inside the owner object but failed, https://code.sololearn.com/c1PBlh8mYYRg/?ref=app
22 Réponses
+ 3
#Like this : Lenoname
ownerlist = []
petlist = []
class hamster :
def __init__ (self, typeofpet, name, gender, age) :
self.typeofpet = typeofpet
self.name = name
self.gender= gender
self.age = age
def __str__(self) :
return f" {self.typeofpet}, {self.name}, {self.gender}, {self.age}"
class owner :
def __init__ (self, name, lastname, pets) :
self.name = name
self.lastname = lastname
self.pets = pets
def __str__(self) :
return f"{self.name}, {self.lastname},{self.pets}"
pet1 = hamster('hamster', 'pell', 'male', 2)
petlist.append(pet1)
owner1 = owner('p1', 'son', petlist[0])
ownerlist.append(owner1)
for a in ownerlist:
print(a)
+ 4
__str__ should return a str not print a str
So you can just write print(a) in your for loop.
And you give onwer1 1 pet not the complete list.
But in your onwer class you act with your for loop like that you expect a list.
+ 2
Depends on what you want.
If you want use petlist[0] you could change your owner class.
Or you could write something like this.
[petlist[0]]
so you have a list.
+ 2
Lenoname , sorry, why didn't you create a superclass from which to derive the subclasses of each animal (hamster, cat etc.)?
I don't say you are wrong or there is something wrong in your code...
Just to be simpler...
+ 1
Jayakrishna🇮🇳 worked
0
Stefanoo what should i do instead?
0
Stefanoo semi worked now i get p1 son [<__main__.hamster…..
0
FF9900 Jayakrishna🇮🇳 Is it possible to give owner1 another pet? I dont mean to replace it, i mean give him one more pet. In that case how?
0
ownerlist[0].append(petlist[1])
Or
owner1.append(petlist[1]) will not work
0
FF9900 its not working,plz check the code again
0
FF9900 i did the same check line 63 in the original program, didnt work
0
The methods at 38
0
FF9900 yeah i did
0
On replit though not here, thats why u still see print
0
Attribute error Hamster object has no attribute ”append”
0
FF9900 im on replit like i said
0
FF9900 Ok updated here also
0
FF9900 awesome, if i could only print them out in more orderly fashion that would be even better, alternatively have the pets inside [ ] or anything similar
0
FF9900 hehe ok
0
Raffaele Bisogno what good would it do? Would it make things less complicated?