Change message when an object is printed #
Now that we have our own MyStr class, let's see the difference between when MyStr and str objects are printed.
normal_str = str("Python is awesome!")
print(normal_str) # Output: Python is awesome!
my_str = MyStr("Python is awesome!")
print(my_str) # <__main__.MyStr object at 0x7fd0908896c0>
When MyStr object is printed, the message displays the type of the object, along with the position in the memory, which isn't very useful. We want the message to be the same as str object.
Special method: __str__ #
The __str__ method is a special method that provides a string representation of an object. It is called by the built-in str() function and the print() function when attempting to convert an object to a string.
For example:
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f"This is a dog named {self.name}"
max_the_dog = Dog("Max")
print(max_the_dog) # This is a dog named Max
In the example above, we create a new class, Dog, which accepts an argument when constructed. The value of name is then set as an object property, conveniently named name. We then defined the method __str__, which returns a string to be the message when a Dog object is printed.
Now that we know how to use the method __str__, let's implement it in our MyStr class.
Exercise #
- Update the
__init__method to set the propertytextin ourMyStrclass and implement the__str__method to return the value oftextproperty.
Tests #
MyStr("Python is awesome")should create an object with following attributes:- Property
textshould be"Python is awesome!"
- Property
MyStr("Programming is fun")should create an object with following attributes:- Property
textshould be"Programming is fun"
- Property
print(MyStr("Python is awesome!"))should print the message"Python is awesome!"
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules