def__str__(self) -> str: returnf'This is a {self.__color} apple.[Print by __str__]'
def__init__(self, color): self.__color = color
1 2 3 4 5 6 7 8 9 10
λ python Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 252020, 23:03:10) [MSC v.191664 bit (AMD64)] on win32 Type"help", "copyright", "credits"or"license"for more information. >>> from base_knowledge import Apple >>> red_apple = Apple("red") >>> red_apple <base_knowledge.Apple object at 0x000002BCE2110AF0> >>> print(red_apple) This is a red apple.[Print by __str__] >>>
从以上输出,
print调用了__str__
交互式环境,直接输出了地址信息
Condition 2
只重写__repr__
__str__调用父类
1 2 3 4 5 6 7 8 9 10
classApple(object):
def__repr__(self) -> str: returnf'This is a {self.__color} apple.[Print by __repr__]'
def__str__(self) -> str: returnsuper().__str__()
def__init__(self, color): self.__color = color
1 2 3 4 5 6 7 8 9 10
λ python Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 252020, 23:03:10) [MSC v.191664 bit (AMD64)] on win32 Type"help", "copyright", "credits"or"license"for more information. >>> from base_knowledge import Apple >>> red_apple = Apple("red") >>> red_apple This is a red apple.[Print by __repr__] >>> print(red_apple) This is a red apple.[Print by __repr__] >>>
从以上输出,
交互式环境, 调用了重写的__repr__
print也调用了__repr__
Condition 3
重写__str__
重写__repr__
1 2 3 4 5 6 7 8 9 10
classApple(object):
def__repr__(self) -> str: returnf'This is a {self.__color} apple.[Print by __repr__]'
def__str__(self) -> str: returnf'This is a {self.__color} apple.[Print by __str__]'
def__init__(self, color): self.__color = color
1 2 3 4 5 6 7 8 9 10
λ python Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 252020, 23:03:10) [MSC v.191664 bit (AMD64)] on win32 Type"help", "copyright", "credits"or"license"for more information. >>> from base_knowledge import Apple >>> red_apple = Apple("red") >>> red_apple This is a red apple.[Print by __repr__] >>> print(red_apple) This is a red apple.[Print by __str__] >>>
从以上输出,
交互式环境, 直接输出, 调用了__repr__
print, 调用了__str__
Condition 4
都没重写
1 2 3 4
classApple(object):
def__init__(self, color): self.__color = color
1 2 3 4 5 6 7 8 9 10
λ python Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 252020, 23:03:10) [MSC v.191664 bit (AMD64)] on win32 Type"help", "copyright", "credits"or"license"for more information. >>> from base_knowledge import Apple >>> red_apple = Apple("red") >>> red_apple <base_knowledge.Apple object at 0x0000025ABFE10AF0> >>> print(red_apple) <base_knowledge.Apple object at 0x0000025ABFE10AF0> >>>