Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Learning Python
Learning Python

Python Tutorial

  • How to Learn Python
  • Python 运行与开发环境
    • Python 交互式控制台
    • How to Run a Python Program?
    • IDEs for Python
    • Run Console Script and Pause
    • Remove/Clean pycache Folders
    • Python注释与文档字符串使用指南
    • Python 文件头部声明:Shebang 和编码
    • * 整除和取模运算的实际应用场景
    • * Legacy Python2 Division Behavior
  • List
    • List and Tuple Tutorial 1
    • List and Tuple Tutorial 2
    • 案例:个人书单管理系统
    • 案例:表格合并 List Merge
    • 二维数据结构:列表与数组对比学习
    • List 无限嵌套 (Example)
    • List Methods
    • List - A Complete Guide
    • List Comprehension - A Short Guide
    • When to use list comprehension
    • Inheriting From list vs UserList
    • Flatten a List of Lists
    • Stacks, Queues, and Priority Queues
    • 列表推导式与f字符串
    • Lab 1.1 - List Methods Tutorial
    • Lab 1.3 - Python 编程实验指导:2维List高级排序
  • String
    • Python String
    • Python 字符串格式化实战
    • String Format 举例
    • 多行字符串缩进与空格处理
    • Lab 1.2 - Python 字符串处理实战
  • Dict
    • Dict 字典 Tutorial 1
    • 案例: 合并表格使用 Dict
    • Dict Tutorial 2
    • Dict Set Default Tutorial
    • Dict Set Default Tutorial Examples
    • Python dict.get(default) 遇到 None
    • Dict Json vs Pickle
    • Multi Lookup Keys Dict
    • Python Dict Vs Database
    • Python Counter Demo
    • The Pythonic Way to Count
    • 如何高效实现有序Dict?
  • Function and Module
    • 快速了解 Python 函数
    • 函数及其参数(提高)
    • Args and Kwargs
    • Python 星号解包
    • Lambda Function
    • Module Tutorial
    • python中跨目录(文件)import函数
    • PPT
  • Class and OOP
    • Object Oriented Programming
    • Instance Class Static Mathods
    • Inheritance And Composition
    • Print Overridden
    • init 的显示与隐式调用
  • 科学计算与可视化
    • NumPy和Matplotlib快速入门教案
    • Lab 2.1 高效学习NumPy实验
    • Lab 2.2 高效学习Matplotlib绘图实验
  • 课堂练习列表
Back to top
View this page

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)

(ref)

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 ...

Reference¶

what-is-the-difference-between-str-and-repr

Next
init 的显示与隐式调用
Previous
Inheritance And Composition
Copyright © 2025, scuec
Made with Sphinx and @pradyunsg's Furo
On this page
  • Print Overridden
    • Point Example
    • Return a Name
    • datetime example
    • Reference