在讲解之前,我们先来了解下str和repr的区别:两者都是用来将数字,列表等类型的数据转化为字符串的形式。不同之处在于str更加类似于C语言中使用printf输出的内容,而repr输出的内容会直接将变量的类型连带着表现出来。
例如:
>>> print (str('Python')) Python >>> print (repr('Python')) 'Python'
下面我通过一个例子进一步阐述__str__与__repr__两个魔法函数的区别。
>>> class Test(): def __inint__(self): self.data = 'Hello,World!' >>> test = Test() >>> test <__main__.Test object at 0x0000000003345A90> >>> print (test) <__main__.Test object at 0x0000000003345A90>
不难看出:无论是直接输出对象,还是通过print对象,都是显示对象的内存地址。
这样的数据对于用户和开发人员来说,都不是很友好。
对此,Python专门为我们引入__str__和__repr__两个函数。
1.重构__str__方法
>>> class Test(): def __str__(self): return "Hello,World!" >>> test = Test() >>> test <__main__.Test object at 0x00000000031EAB00> >>> print (test) Hello,World!
重构后,直接输出对象还是显示内存地址,而通过print能打印出格式化字符串。
2.重构__repr__方法
>>> class Test(): def __repr__(self): return 'Hello,World!' >>> test = Test() >>> test Hello,World! >>> print (test) Hello,World!
重构后,无论是直接输出对象,还是通过print对象,都能输出格式化字符串
由此可以分析出__str__()和__repr__()的区别:前者是用于显示给用户,而后者用于显示给开发人员(程序员)。