_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__