如何实现Python按日期选对象并邮件分行展示其属性?
解决方案
方法1:手动拼接键值对(精准匹配需求格式)
直接遍历对象属性字典,逐个拼接每行内容,按需处理逗号:
# 获取对象属性字典 obj_attrs = vars(today_object) attr_items = list(obj_attrs.items()) content_lines = [] for idx, (key, val) in enumerate(attr_items): # 拼接当前行的键值对 line = f"'{key}': '{val}'" # 除了最后一行,其余行末尾加逗号 if idx != len(attr_items) - 1: line += "," content_lines.append(line) # 组合成最终格式 formatted_content = "{\n" + "\n".join(content_lines) + "\n}"
生成的内容示例:
{ 'attribute_1': 'attribute_6_1', 'attribute_2': 'attribute_6_2', 'attribute_3': 'attribute_6_3' }
方法2:用pprint模块快速格式化
借助Python内置的pprint模块自动处理多行格式,无需手动拼接:
from pprint import pformat obj_attrs = vars(today_object) # 调整参数让每个键值对单独占一行,无缩进 formatted_content = pformat(obj_attrs, indent=0, width=1)
输出效果和需求基本一致,适合快速实现。
方法3:自定义类的字符串表示
如果需要多次使用这种格式,可以在类中重写__str__方法,直接返回格式化后的内容:
class Class: def __init__ (self, attribute_1, attribute_2, attribute_3): self.attribute_1 = attribute_1 self.attribute_2 = attribute_2 self.attribute_3 = attribute_3 def __str__(self): return ( "{\n" f"'attribute_1': '{self.attribute_1}',\n" f"'attribute_2': '{self.attribute_2}',\n" f"'attribute_3': '{self.attribute_3}'\n" "}" )
之后直接调用str(today_object)就能得到目标格式。
内容的提问来源于stack exchange,提问作者EGL
相关产品推荐
相关产品推荐

