温馨提示×

在Python中优雅地打印对象

小樊
83
2024-06-24 23:26:38
栏目: 编程语言

要在Python中优雅地打印对象,可以使用内置的__str____repr__方法来定制对象的字符串表示。

例如,假设有一个名为Person的类:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Person: {self.name} ({self.age} years old)"

    def __repr__(self):
        return f"Person(name={self.name}, age={self.age})"

在上面的示例中,__str__方法用于返回对象的友好字符串表示,而__repr__方法用于返回对象的原始表示。这样,在打印对象时,将会自动调用这两个方法。

person = Person("Alice", 30)
print(person)  # 输出:Person: Alice (30 years old)
print(repr(person))  # 输出:Person(name=Alice, age=30)

通过定制__str____repr__方法,可以让打印对象更加优雅和易读。

0