Python: Understanding _ STR __

Source: Internet
Author: User

Here is my understanding. If there is something wrong with me. Please be sure to tell me. Thank you!

In python, __str _ is generally in this format.

Class:

Def _ STR _ (Self ):

Return "this is in Str"

In fact, __str _ is called by the print function. Generally, it is a return object. This is represented in a string. If the STR () function is not used for conversion. When printing a class, print first calls the _ STR __defined in the class, for example, 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. py

Init: This is only test

STR: This is only test

As shown in the preceding example, when a strtest instance st is printed, the __str _ function is called.

In fact, basically all objects in Python have _ STR _ by default for the print function. For example, the _ STR __in the dictionary can be found in the red part:

>>> Dir ({})
['_ Class _', '_ CMP _', '_ ins INS _', '_ delattr __', '_ delitem _', '_ Doc _', '_ eq _', '_ format _', '_ Ge __', '_ getattribute _', '_ getitem _', '_ GT _', '_ Hash _', '_ init __', '_ ITER _', '_ Le _', '_ Len _', '_ LT _', '_ ne __', '_ new _', '_ reduce _', '_ performance_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 # equals to print T
{'1': 'hello', '2': 'World '}
>>> T. _ STR __()
"{'1': 'hello', '2': 'World '}"

We can see that print T is the same as T. _ STR. Only _ STR _ () outputs the dictionary content as a string.

Let's take a look at the example below. If the returned result in function _ STR _ is not a string, 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.valif __name__ == "__main__":    st=strtest()    print st

$./Str1.py

Traceback (most recent call last ):
File "./Str. py", line 12, in <module>
Print St
Typeerror: _ STR _ returned non-string (type INT)

Error message: __str _ A non-string is returned. At this time, we should do this: 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 use STR () to convert the integer type to the struct type.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.