DEV Community

Cover image for Intro to Python: Day 15 - OOP - Overriding the Print Method on a Custom Class
James Hubert
James Hubert

Posted on • Edited on

Intro to Python: Day 15 - OOP - Overriding the Print Method on a Custom Class

Hi there 👋 I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

So every programming language has its own built-in behavior for printing different kinds of objects. In Python, if you have a custom class, printing an instance of the class will simply print a pointer which indicates its place in your storage. It's pretty useless.

class Animal():
    def __init__(self, type):
        self.type = type

lion = Animal("lion") 

print(lion)

# prints "<Lion object at 0xa0acf8>"
Enter fullscreen mode Exit fullscreen mode

(Note: This example is adapted from the super duper helpful OOP course at dev.to)

So, if we want to override the built-in print functionality, all we need to do is specify it using the built-in instance method __str__().

class Animal():
    def __init__(self, type):
        self.type = type

    def __str__(self):
        return f"I am a {self.type} type of animal."

lion = Animal("lion") 

print(lion)

# prints "I am a lion type of animal."
Enter fullscreen mode Exit fullscreen mode

Pretty cool eh? If you're working extensively with custom classes, having them be able to show useful information when printed can be useful.

If you like projects like this and want to stay up to date with more, check out my Twitter @stonestwebdev, I follow back! See you tomorrow for another project.

Top comments (0)