Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Printing an Object

What happens when you print a pet?

class Pet:
    def __init__(self, name, species, age):
        self.name = name
        self.species = species
        self.age = age

rex = Pet("Rex", "dog", 3)
print(rex)
<Pet object at 0x1655900>

Python doesn't know how a pet should look as text, so it prints the kind of object and where the object is stored in the computer's memory. That number is different from run to run, and it tells you nothing about Rex.

You can tell Python what to show with a method named __str__, with two underscores on each side again. It returns the text for the object, and Python calls it by itself whenever the object has to become text: in print(), in an f-string and in str():

class Pet:
    def __init__(self, name, species, age):
        self.name = name
        self.species = species
        self.age = age

    def __str__(self):
        return f"{self.name} the {self.species}"

rex = Pet("Rex", "dog", 3)
print(rex)
print(f"My pet: {rex}")
Rex the dog
My pet: Rex the dog

You don't call __str__ yourself, just as you don't call __init__. The two underscores mark Python's own special methods, which Python calls at the right moment: __init__ when an object is created, __str__ when it has to be shown as text. The names can't be mixed up with methods of your own, such as describe().

__str__ has to return the text. When it prints the text instead, it returns None, and the program prints the text and then ends with TypeError: __str__ returned non-string (type NoneType).

Instructions

  1. 1

    Run the program: it prints <Pet object at 0x…>. Add a method __str__ to the class that returns the pet's name, species and age like this: Rex (dog, 3 years). print(rex) then prints exactly that. Keep the lines that create Rex and Kiwi as they are.

  2. 2

    Below, print Kiwi in a sentence with an f-string: Best friend: Kiwi (parrot, 4 years).

Back

6/11

  1. 1. A Class and Its Objects
  2. 2. Attributes
  3. 3. Methods
  4. 4. Methods That Change the Object
  5. 5. Quiz: Objects
  6. 6. Printing an Object
  7. 7. A List of Objects
  8. 8. Inheritance
  9. 9. Quiz: Inheritance
  10. 10. super()
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.