Print Overridden¶
Override 重载(改写,覆盖)用于类,它使得新类在使用 Python 内置函数(或符号)时,功能可以定制。
例如,希望 print(object) 时,按照特别的格式打印 object 的关键属性 :
object.__str__, object.__repr__ 是为了解决程序运行过程中在屏幕上打印字符的形式
__repr__()goal is to be unambiguous__str__()goal is to be readable
Point Example¶
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __repr__(self):
... return 'Point(x=%s, y=%s)' % (self.x, self.y)
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
Return a Name¶
class WordNetLemmatizer(object):
def __init__(self):
pass
def __repr__(self):
return "<WordNetLemmatizer>"
# 仅仅只返回一个名字,有提示作用
__repr__()为程序员提供了对象的官方字符串表示法。__str__()为用户提供了对象的非正式字符串表示。
datetime example¶
>>> import datetime
>>> today = datetime.datetime.now()
>>> today
datetime.datetime(2023, 2, 18, 18, 40, 2, 160890)
>>> print(today)
2023-02-18 18:40:02.160890
换句话说: __repr__() 的格式可以用来直接作为类的实例化
>>> new_date = datetime.datetime(2023, 2, 18, 18, 40, 2, 160890)
>>> new_date == today
True
>>> new_date = 2023-02-18 18:40:02.160890
Traceback (most recent call last):
...
File "<input>", line 1
new_date = 2023-02-18 18:40:02.160890
^
SyntaxError: leading zeros in decimal integer literals are not permitted ...