Python's Magic Method for representation of class?

Question:

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?

Asked By: alabamajack

||

Answers:

You need to implement __str__

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

    def get_name(self):
        return self.__name

    def __str__(self):
        return self.get_name()

f = foo("My name")

print f
Answered By: Leon

You need to override __str__() method like this:

class b:
     def __str__(self)
             return "hello"

n = b()

print n
hello
Answered By: Dmitry Zagorulkin

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.

Answered By: Noufal Ibrahim
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.