class Dog6: def __init__(self, initial_name): self._name = initial_name def get_self(self): return self def __str__(self): # # Implement this! # return __ def __repr__(self): return "<Dog named '" + self._name + "'>" def test_inside_a_method_self_refers_to_the_containing_object(self): fido = self.Dog6("Fido") self.assertEqual(__, fido.get_self()) # Not a string! def test_str_provides_a_string_version_of_the_object(self): fido = self.Dog6("Fido") self.assertEqual("Fido", str(fido)) def test_str_is_used_explicitly_in_string_interpolation(self): fido = self.Dog6("Fido") self.assertEqual(__, "My dog is " + str(fido)) def test_repr_provides_a_more_complete_string_version(self): fido = self.Dog6("Fido") self.assertEqual(__, repr(fido)) def test_all_objects_support_str_and_repr(self): seq = [1, 2, 3] self.assertEqual(__, str(seq)) self.assertEqual(__, repr(seq)) self.assertEqual(__, str("STRING")) self.assertEqual(__, repr("STRING"))
时间: 2024-02-23 21:57:48 浏览: 76
Here is the completed code with the missing parts:
```
class Dog6:
def __init__(self, initial_name):
self._name = initial_name
def get_self(self):
return self
def __str__(self):
return self._name
def __repr__(self):
return "<Dog named '" + self._name + "'>"
def test_inside_a_method_self_refers_to_the_containing_object(self):
fido = Dog6("Fido")
self.assertEqual(fido, fido.get_self()) # Not a string!
def test_str_provides_a_string_version_of_the_object(self):
fido = Dog6("Fido")
self.assertEqual("Fido", str(fido))
def test_str_is_used_explicitly_in_string_interpolation(self):
fido = Dog6("Fido")
self.assertEqual("My dog is Fido", "My dog is " + str(fido))
def test_repr_provides_a_more_complete_string_version(self):
fido = Dog6("Fido")
self.assertEqual("<Dog named 'Fido'>", repr(fido))
def test_all_objects_support_str_and_repr(self):
seq = [1, 2, 3]
self.assertEqual("[1, 2, 3]", str(seq))
self.assertEqual("[1, 2, 3]", repr(seq))
self.assertEqual("STRING", str("STRING"))
self.assertEqual("'STRING'", repr("STRING"))
```
Note that in `test_str_is_used_explicitly_in_string_interpolation`, the expected output is `"My dog is Fido"` instead of `"My dog is <Dog named 'Fido'>"` because the `+` operator implicitly calls `str` on the object being concatenated.
阅读全文