在 Python 中更改类的字符串表示形式

在 Python 中更改类的字符串表示

Change the string representation of a Class in Python

使用该__str__()方法更改类的字符串表示形式。
__str__()方法由str(object)内置函数format()
print()函数调用,并返回对象的非正式字符串表示形式。

主程序
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return f'Employee name: {self.name}' emp = Employee('Alice', 100) print(emp) # 👉️ Employee name: Alice

我们在类上定义了__str__()方法来更改其字符串表示形式。

_
_ str _ _ ()
方法由
内置
str(object)函数format()print()
函数调用,并返回对象的非正式字符串表示形式。

print()函数返回__str__()方法的输出。

主程序
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return f'Employee name: {self.name}' emp = Employee('Alice', 100) print(emp) # 👉️ Employee name: Alice

确保从该方法返回一个字符串__str__(),否则
TypeError会引发 a。

主程序
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): # 👇️ returned integer but must be string return self.salary emp = Employee('Alice', 100) # ⛔️ TypeError: __str__ returned non-string (type int) print(emp)

如果您需要返回一个整数,请使用str()该类将其转换为字符串。

主程序
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): # 👇️ convert integer to string return str(self.salary) emp = Employee('Alice', 100) print(emp) # 👉️ 100

如果您在格式化字符串文字中或与该方法__str__()一起使用该对象,则会调用该str.format()方法。

主程序
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) emp = Employee('Alice', 100) result = f'Salary: {emp}' print(result) # 👉️ Salary: 100

__str__()方法应返回一个字符串,该字符串是对象的人类可读表示形式。

还有一种__repr__()方法可以类似地使用。

主程序
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name emp = Employee('Alice', 100) print(emp) # 👉️ Alice print(repr(emp)) # 👉️ Alice

_
_ repr _ _
方法由函数调用,
通常
repr()用于获取字符串,该字符串可用于使用eval()函数重建对象。

If the class doesn’t have the __str__() method defined, but has __repr__()
defined, the output of __repr__() is used instead.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name emp = Employee('Alice', 100) result = f'Employee name: {emp}' print(result) # 👉️ Employee name: Alice

A good way to illustrate the difference between __str__() and __repr__() is
to use the datetime module.

main.py
import datetime # 👇️ using __str__() print(datetime.datetime.now()) # 👉️ 2022-09-04 16:47:40.839871 # 👇️ using __repr__() # 👉️ datetime.datetime(2022, 9, 4, 16, 47, 57, 981219) print(repr(datetime.datetime.now())) result = eval('datetime.datetime(2022, 9, 4, 16, 47, 57, 981219)') print(result) # 👉️ 2022-09-04 16:47:57.981219

When we used the print() function, the __str__() method in the datetime
class got called and returned a human-readable representation of the date and
time.

When we used the repr() function, the __repr__() method of the class got called and returned a string that can be used to recreate the same state of the object.

We passed the string to the eval() function and created a datetime object
with the same state.

Note that implementing the __repr__() method in this way is not always
necessary or possible.

大多数时候让__str__()方法返回一个人类可读的字符串就足够了。