--- title: Print Overridden fid: 20240929-171359 tags: --- # Print Overridden Override 重载(改写,覆盖)用于类,它使得新类在使用 Python 内置函数(或符号)时,功能可以定制。 例如,希望 print(object) 时,按照特别的格式打印 object 的关键属性 : ``` {.python} def __srt__(self,): return "formatted string {}".format(self.an_attribute) ``` `object.__str__`, `object.__repr__` 是为了解决程序运行过程中在屏幕上打印字符的形式 - `__repr__()` goal is to be unambiguous - `__str__()` goal is to be readable ## Point Example ``` python >>> 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) ``` [(ref)](https://www.nltk.org/_modules/nltk/stem/wordnet.html) ## Return a Name ```python class WordNetLemmatizer(object): def __init__(self): pass def __repr__(self): return "" # 仅仅只返回一个名字,有提示作用 ``` - `__repr__()` 为程序员提供了对象的官方字符串表示法。 - `__str__()` 为用户提供了对象的非正式字符串表示。 ## datetime example ``` python >>> 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__()` 的格式可以用来直接作为类的实例化 ``` python >>> 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 "", line 1 new_date = 2023-02-18 18:40:02.160890 ^ SyntaxError: leading zeros in decimal integer literals are not permitted ... ``` ## Reference [what-is-the-difference-between-str-and-repr](https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr)