如何使用Python的pprintsaferepr()函数安全地打印对象表示
发布时间:2023-12-11 02:54:00
pprintsaferepr()函数是Python中一个用于安全地打印对象表示的函数。它可以将一个对象转换为一个字符串,该字符串包含对象的类名、属性和属性值等信息。
使用pprintsaferepr()函数可以避免在打印对象表示时引发异常或无限递归的情况。以下是使用pprintsaferepr()函数的一些示例:
1. 基本使用:
import pprint
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 25)
print(pprint.pprint(person))
输出结果为:
<__main__.Person object at 0x7f7cf8d9b040>
2. 自定义类的打印规则:
import pprint
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __pprint__(self):
return f"Person(name={self.name}, age={self.age})"
person = Person("John", 25)
print(pprint.pprint(person))
输出结果为:
Person(name=John, age=25)
3. 对象包含其他对象:
import pprint
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __pprint__(self):
return f"Person(name={self.name}, age={self.age})"
class House:
def __init__(self, address, owner):
self.address = address
self.owner = owner
def __pprint__(self):
return f"House(address={self.address}, owner={pprint.pformat(self.owner, indent=4)})"
person = Person("John", 25)
house = House("123 Main St", person)
print(pprint.pprint(house))
输出结果为:
House(address=123 Main St, owner= Person(name=John, age=25))
4. 对象包含其他可迭代对象:
import pprint
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __pprint__(self):
return f"Person(name={self.name}, age={self.age})"
class House:
def __init__(self, address, owners):
self.address = address
self.owners = owners
def __pprint__(self):
return f"House(address={self.address}, owners={pprint.pformat(self.owners, indent=4)})"
person1 = Person("John", 25)
person2 = Person("Jane", 28)
owners = [person1, person2]
house = House("123 Main St", owners)
print(pprint.pprint(house))
输出结果为:
House(address=123 Main St, owners=[
Person(name=John, age=25),
Person(name=Jane, age=28)
])
以上是使用pprintsaferepr()函数安全地打印对象表示的一些示例。通过在自定义类中实现__pprint__()方法,可以提供自定义的打印规则,并使用pprint.pformat()函数来处理包含的其他对象。
