Search code examples
pythonclassoopincompatibility

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


Often, when using a Python Package, I find myself using the str() function to convert a package's custom data-type to a string. If I were to try and create a Python Class for a module, how would I add compatibility to str() function for my package's class? example:

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)

Solution

  • def __str__(self): will be used when you try to str(my_object). It would also be called in string interpolation such as f'This is my object: {my_object}'

    def __repr__(self): will be used to represent your object in a console

    >>> 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