博客
关于我
` __str__ 和 __repr__`
阅读量:280 次
发布时间:2019-03-01

本文共 1266 字,大约阅读时间需要 4 分钟。

__str__ 和 __repr__

一、__str__

  • 触发条件:当使用 print() 函数输出对象时,会调用 __str__ 方法。

    class Person:        def __init__(self, name):            self.name = name        def __str__(self):            print("打印对象时触发了__str__")            return f"对象名字:{self.name}"    P1 = Person("淘小欣")    P2 = Person("乔布斯")    print(P1)  # 输出内容:打印对象时触发了__str__对象名字:淘小欣    print(P2)  # 输出内容:打印对象时触发了__str__对象名字:乔布斯    print(P2.name)  # 输出:乔布斯
  • 返回一个看起来字典格式的字符串示例。

    # 示例一:    class Person:        def __init__(self, name, age):            self.name = name            self.age = age        def __str__(self):            return f"{self.__dict__}"    P1 = Person("库克", 99)    print(P1)  # 输出:{'name': '库克', 'age': 99}    # 示例二:    import json    class Person:        def __init__(self, name, age):            self.name = name            self.age = age        def __str__(self):            return json.dumps(self.__dict__)    P1 = Person("淘小欣", 22)    print(P1)  # 输出:{"name": "淘小欣", "age": 22}

二、__repr__

  • 触发条件:在命令窗口中直接写对象时,会调用 __repr__ 方法。

    class Person:        def __init__(self, name):            self.name = name        def __repr__(self):            print("命令窗口直接写对象触发了__repr__")            return f"名字 : {self.name}"    P1 = Person("佩奇")    >>> P1  # 输出:命令窗口直接写对象触发了__repr__名字 : 佩奇    >>> P1.name  # 输出:佩奇

转载地址:http://kwxo.baihongyu.com/

你可能感兴趣的文章
python 抓取网页内容
查看>>
python 按照当前日期创建文件
查看>>
Python 接口并发测试详解
查看>>
Python 接口自动化 —— requests框架
查看>>
python 接口自动化数据结构(如列表、字典、元组)
查看>>
Python 接口自动化测试中的深拷贝与浅拷贝~
查看>>
Python 接口自动化测试中的高阶函数
查看>>
python 控制 cmd 命令行颜色
查看>>
Python 操作 Azure Blob Storage
查看>>
Python 操作 Excel 全攻略 | 包括读取、写入、表格操作、图像输出和字体设置
查看>>
Python 操作 JMeter 探索:pymeter 实操指南
查看>>
Python 操作 Redis
查看>>
Python 操作Mysql(PyMysql)
查看>>
Python 操作Redis
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(一)
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(二)
查看>>
Python 数据文件与网络数据序列化存储详解
查看>>
Python 数据结构与算法详解
查看>>
Python 数据采集、清洗、整理、分析以及可视化实战
查看>>
Python 数据预处理
查看>>