The following is my understanding if there is anything wrong with me. Please do tell me. Thank you very much!
In The Python language, successie __str__ is usually formatted this way.
class A:
def __str__(self):
return “this is in str”
Literally, ___ is called by the print function, usually return something. This thing should be in the form of a string. If you don’t want to use the STR () function. If you print a class, print first calls each ___ by str__, such as STR. Py
#!/usr/bin/env python
class strtest:
def __init__(self):
print "init: this is only test"
def __str__(self):
return "str: this is only test"
if __name__ == "__main__":
st=strtest()
print st
$./str.pyinit: this is only test
str: this is only test
As you can see from the above example, the function with ___ is called when you print an instance of STRtest st.
By default, the python objects almost always have the __str__ function used by print. S the dictionary with ___, see the red part:
> > > dir({})
[‘__class__’, ‘__cmp__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘has_key’, ‘items’, ‘iteritems’, ‘iterkeys’, ‘itervalues’, ‘keys’, ‘pop’, ‘popitem’, ‘setdefault’, ‘update’, ‘values’]
> > > t={}
> > > t[‘1’] = “hello”
> > > t[‘2’] = “world”
> > > t
# is equal to print t
{‘1’: ‘hello’, ‘2’: ‘world’}
> > > t.__str__()
“{‘1’: ‘hello’, ‘2’: ‘world’}”
You can see a dictionary, print t and t. str__() are the same. Simply output the contents of the dictionary as a string.
If it’s not a string returned in the function ___, see str1.py
#!/us/bin/env/python
#__metaclass__ = type
#if __name__ == "__main__":
class strtest:
def __init__(self):
self.val = 1
def __str__(self):
return self.val
if __name__ == "__main__":
st=strtest()
print st
$./str1.py
Traceback (most recent call last):
File “./ STR. Py “, line 12, in < module>
print st
TypeError: ___, returned non-string (type int)
Error message with: ___ returned a non-string. Here’s what we should do: see str2. Py
#!/usr/bin/env python
#__metaclass__ = type
#if __name__ == "__main__":
class strtest:
def __init__(self):
self.val = 1
def __str__(self):
return str(self.val)
if __name__ == "__main__":
st=strtest()
print st
$./str2.py
1
We used STR () to change the integer to a character.