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.
Read More:
- Differences between length() size() and C strlen() of C + + string member functions
- Detailed explanation of Python__ new__() method
- panic: runtime error: index out of range
- Python switch / case statement implementation method
- Implementation of Python switch / case statements
- From in Python__ future__ The role of import *
- The conversion between [Python] bytes and hex strings.
- Python2 PicklingError: Can‘t pickle <type ‘instancemethod‘>: attribute lookup __builtin__.instanceme
- Missing parents in call to ‘print’
- C++:error C2228: left of ‘.str’ must have class/struct/union
- Tensorflow in function tf.Print Method of outputting intermediate value
- Java compareto() method
- Running Python 3.7 web.py Runtimeerror: generator raised stopiteration exception occurred during test
- Translate() and maketrans() methods of string in Python
- C++ string substr()
- The use of C + + template function and lambda expression
- Time, strftime and strptime in Python
- RuntimeError: each element in
- C++ foundation — clear/erase/pop of string class_back
- Solve the problem of error: cannot pass objects of non trivially copyable type ‘STD:: String’ in C / C + +