如何使 Python str() 函数与自定义 class 一起使用?

How to make the Python str() function work with a custom class?

通常,在使用 Python 包时,我发现自己使用 str() 函数将包的自定义数据类型转换为字符串。如果我要尝试为模块创建 Python Class,我将如何为我的包的 class 添加 str() 函数的兼容性? 示例:

class Person:
  def __init__(self, name, age, likes, dislikes):
    self.name = name
    self.personality = {
      "likes": likes,
      "dislikes": dislikes
}

bill = Person("bill", 21, ["coding", "etc"], ["interviews", "socialising"])
strBill = str(bill) # This will store: '<__main__.Person object at 0x7fa68c2acac8>' but I want a dictionary containing all of the variables stored in this 'bill' class


print(strBill)

def __str__(self): 将在您尝试 str(my_object) 时使用。它也会在字符串插值中调用,例如 f'This is my object: {my_object}'

def __repr__(self): 将用于在控制台中表示您的对象

>>> class A():
...     def __str__(self):
...             return 'im a string nicely formatted'
...     def __repr__(self):
...             return 'class A object'
...
>>> a = A()
>>> print(a)
im a string nicely formatted
>>> a
class A object