龙空技术网

Python入门题042:__str__和__repr__的区别

写代码的安徒生 318

前言:

今天各位老铁们对“python转str”都比较注重,小伙伴们都想要剖析一些“python转str”的相关内容。那么小编在网上收集了一些有关“python转str””的相关知识,希望兄弟们能喜欢,咱们一起来了解一下吧!

题目:

举例说明 __str__ 和 __repr__ 的用法,以及相互的关系。

#python #魔法方法 #魔法函数

视频教程:

Python入门题042:__str__和__repr__的区别

代码1:

class StudentBase:    name: str    score: float    def __init__(self, name, score):        self.name = name        self.score = scoreclass Student(StudentBase):    def __str__(self):        return f'{self.name}:{self.score}分'# 直接输出对象的 id 信息print(StudentBase('mike', 70))# <__main__.StudentBase object at 0x10bf29f70># 输出自定义的、适合人类阅读的信息print(Student('mike', 70))# mike:70分# 在容器中不会调用 __str__print([Student('mike', 70), Student('john', 60)])# [<__main__.Student object at 0x10a631fa0>, <__main__.Student object at 0x10a631e50>]

代码2:

class Student:    name: str    score: float    def __init__(self, name, score):        self.name = name        self.score = score    def __str__(self):        return f'{self.name}:{self.score}分'    def __repr__(self):        return f'<{self.__class__.__name__}: {self.name},{self.score}分>'print(Student('mike', 70))# mike:70分# 在容器中调用了 __repr__print([Student('mike', 70), Student('john', 60)])# [<Student: mike,70分>, <Student: john,60分>]

代码3:

class Student:    name: str    score: float    def __init__(self, name, score):        self.name = name        self.score = score    def __repr__(self):        return f'<{self.__class__.__name__}: {self.name},{self.score}分>'# 没有 __str__ 的情况下,直接调用 __repr__print(Student('mike', 70))# <Student: mike,70分># 在容器中调用了 __repr__print([Student('mike', 70), Student('john', 60)])# [<Student: mike,70分>, <Student: john,60分>]

标签: #python转str