Converting objects to strings error | Sololearn: Learn to code for FREE!
+ 1

Converting objects to strings error

class Animal:     def __init__(self, name, type):         self.name = name         self.type = type     def __add__(self, other):         return Animal(self.name + "-" + other.name, self.type + "/" + other.type) dog = Animal( "Dog", "Canine") lizard = Animal("Lizard", "Reptile") lion = Animal("Lion", "Feline") .... hybrid = input () + lizard print("Hybrid:", hybrid.name) print("Type:", hybrid.type) Output: TypeError: can't convert 'Animal' object to str implicitly . Can anyone help with this?

30th Mar 2017, 12:57 PM
Nuno Moreira
Nuno Moreira - avatar
1 Answer
+ 6
You are trying to add two different types: a string from input() and an object of Animal class. You should define the Animal class' __str__ magic method to explain to Python how to act on converting Animal objects to strings (what exact value to take into consideration).
30th Mar 2017, 7:09 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar