Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I replace the __str__ method of a Python object with another function?

Tags:

python

Here is the code:

class Dummy(object):
    def __init__(self, v):
        self.ticker = v


def main():
        def _assign_custom_str(x):
            def _show_ticker(t):                
                return t.ticker
            x.__str__ = _show_ticker
            x.__repr__ = _show_ticker
            return x


    a = [Dummy(1), Dummy(2)]

    a1 = [_assign_custom_str(t) for t in a]
    print a1[1]
    # print a1[1].__str__ # test to if orig __str__ is replaced

I was hoping to see the output like this

2

However, instead I see the standard representation:

<__main__.Dummy object at 0x01237730>

Why?

like image 265
Anthony Kong Avatar asked May 08 '12 05:05

Anthony Kong


People also ask

What is __ str __ method in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

__str__ is used in to show a string representation of your object to be read easily by others. __repr__ is used to show a string representation of the object.

What is __ add __ in Python?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1.

What is Python __ repr __?

The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object. In other words, if you pass the returned string of the object_name.


1 Answers

Magic methods are only guaranteed to work if they're defined on the type rather than on the object.

For example:

def _assign_custom_str(x):
        def _show_ticker(self):                
            return self.ticker
        x.__class__.__str__ = _show_ticker
        x.__class__.__repr__ = _show_ticker
        return x

But note that will affect all Dummy objects, not just the one you're using to access the class.

like image 91
agf Avatar answered Sep 28 '22 06:09

agf