Representing Objects as Strings
00:00 When you create a new class, it’s important to think about how its object will look when you print them. There are two ways to do this. The user-friendly representation and the developer-friendly representation.
00:13
Let’s start with the user-friendly one. The __str__()
special method returns a human-readable string representation of the object at hand. Python calls this method when you call the built-in str()
function, passing an instance of the class as an argument, and also when you use the instance as an argument to the print()
and format()
functions.
00:40
Let’s go back to the Storage
class and implement the __str__()
method to return a string that indicates both the value and the unit of the instance.
00:53
So far, this is how the Storage
class looks like. So let’s go ahead and add a __str__()
magic method here. def __str__()
passing self
and returning f
for format, and you want to return the value, so {self.value}
space in between and {self.unit}
.
01:24
Alright, now let’s run the code and see what happens when you print storage_size
.
01:32 There you go. You get 512 GB which is exactly what you wanted.
Become a Member to join the conversation.