Special Methods (__str__ and __repr__)
Learn the difference between __str__ and __repr__ and why they are used.
Chirpy is becoming stronger and more powerful day by day! So far, we’ve built a rich ecosystem where users can create posts, interact through likes and comments, and even have verified accounts. But as our platform grows, we run into a small but important issue!
How do we display objects in a meaningful way?
Right now, when we print a User
or Post
object:
user1 = User("alex123", "Alex", "secret89")print(user1)
It shows the output as:
<user.User object at 0x7553bb076270>
Note: The memory would not be the same everytime this is run as memory is allocated on run time and on every run the memory will change. Therefore, we'll have different memory locations everytime. On the current run memory is 0x7553bb076270.
This isn’t very helpful! It doesn’t tell us anything about the user—it just shows a memory location.
Similarly, when we print a post:
post1 = Post("Hello world!", "Alex")print(post1)
We get:
<post.Post object at 0x7f99cd02b430>
Again, this doesn’t give us any useful information about the post.
Wouldn’t it be better if printing a User
showed something like this?
<User: Alex (alex123)>
Or if a Post
gave us a more meaningful summary, like:
<Post by alex123: 'Hello world!', Likes: 5>
To fix this, we need a way to control how our objects are displayed. That’s where Python's special methods come into play!