+ 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?
1 Odpowiedź
+ 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).