Python's special methods __str__ and __repr__

Source: Internet
Author: User

_str__ and __repr__ if you want to turn an instance of a class into STR, you need to implement a special Method __str__ ():classPerson (object):def __init__(self, Name, gender): Self.name=name Self.gender=Genderdef __str__(self):return '(Person:%s,%s)'%(Self.name, Self.gender) Now, under the interactive command line, use thePrintTry :>>> p = person ('Bob','male')>>>Printp (person:bob, male) However, if you hit the variable p directly:>>>P<main. Person object at 0x10c941890>It seems that __str__ () will not be called. Because Python defines both the __str__ () and the __repr__ () methods,__str__() is used to display to the user, and __repr__ () is used to display to the developer. There's a lazy way to define __REPR__:classPerson (object):def __init__(self, Name, gender): Self.name=name Self.gender=Genderdef __str__(self):return '(Person:%s,%s)'%(Self.name, Self.gender)__repr__=__str__tasks, define the __str__ and __repr__ methods for the student class so that you can print out<student:name, Gender, score>:classStudent (person):def __init__(self, name, gender, score): Super (Student, self).__init__(name, gender) Self.score=score? Just add the __str__ () and __repr__ () methods to the students class. Reference code:classPerson (object):def __init__(self, Name, gender): Self.name=name Self.gender=GenderclassStudent (person):def __init__(self, name, gender, score): Super (Student, self).__init__(name, gender) Self.score=scoredef __str__(self):return '(Student:%s,%s,%s)'%(Self.name, Self.gender, Self.score)__repr__=__str__s= Student ('Bob','male', 88)PrintS

Python's special methods __str__ and __repr__

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.