pythonmagic-methods

Python's Magic Method for representation of class?


I have a custom class like:

class foo(object):
    def __init__(self, name):
        self.__name = name
    
    def get_name(self):
         return self.__name

What I want to do is to write

test = foo("test")
print test

instead of

test = foo("test")
print test.get_name()

What is the magic method for doing this?


Solution

  • There are two methods that are relevant. There is the __str__ method which "converts" your object into a string. Then there is a __repr__ method which converts your object into a "programmer representation." The print function (or statement if you're using Python 2), uses the str function to convert the object into a string and then writes that to sys.stdout. str gets the string representation by first checking for the __str__ method and if it fails, it then checks the __repr__ method. You can implement them based on your convenience to get what you want.

    In your own case, implementing a

    def __str__(self):
       return self.__name
    

    should be enough.

    Update: Illustration on Python 3.11.9

     >>> import sys
     >>> sys.version
     '3.11.9 (main, Apr 10 2024, 13:16:36) [GCC 13.2.0]'
     >>> class Foo:
     ...   def __repr__(self):
     ...     return "repr"
     ...   def __str__(self):
     ...     return "string"
     ... 
     >>> f = Foo()
     >>> str(f)
     'string'
     >>> repr(f)
     'repr'
     >>> print (f) # print uses str() to convert f into a string
     string
     >>> 
     >>> f # The repr uses repr() to convert f into the programmer representation
     repr