Complete the code to print the string representation of the object using the __str__ method.
class Person: def __init__(self, name): self.name = name def __str__(self): return f"Person: {self.[1]" p = Person("Alice") print(str(p))
The __str__ method returns a string representation of the object. Here, self.name is used to show the person's name.
Complete the code to define the __repr__ method that returns a string with the class name and the name attribute.
class Person: def __init__(self, name): self.name = name def __repr__(self): return f"Person(name=[1])" p = Person("Bob") print(repr(p))
The __repr__ method should return a string that looks like valid Python code to recreate the object. Using self.name shows the name attribute.
Fix the error in the __str__ method to correctly return the name attribute as a string.
class Animal: def __init__(self, species): self.species = species def __str__(self): return self.[1] cat = Animal("Cat") print(str(cat))
The attribute species is a string, so returning self.species directly works. Using parentheses like a function call causes an error.
Fill both blanks to create a __repr__ method that returns a string with the class name and the species attribute in quotes.
class Animal: def __init__(self, species): self.species = species def __repr__(self): return f"Animal('[1]')" bird = Animal("Bird") print(repr(bird))
The __repr__ method should return a string that looks like valid Python code. Using self.species inside the f-string shows the species attribute.
Fill all three blanks to create a class with __str__ and __repr__ methods that show the name and age attributes properly.
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Name: [1], Age: [2]" def __repr__(self): return f"Person(name=[3], age={{self.age}})" p = Person("Eve", 30) print(str(p)) print(repr(p))
The __str__ method uses self.name and self.age to show the person's details. The __repr__ method uses self.name and self.age to return a string that looks like code to recreate the object.