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?
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.
__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.
The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With