Hướng dẫn __str__ method in python

Hướng dẫn __str__ method in python

Shahpar Khan

Nội dung chính

  • The need for __str__ method:
  • How to call __str__ method
  • 1. Default implementation
  • 2. Custom __str__ method
  • 3. __repr__ method defined only
  • Introduction to the Python __str__ method
  • What is the purpose of str () method?
  • What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?
  • What is __ str __ in Django?
  • What does str () do in Python example?

The need for __str__ method:

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

The __str__ method is called when the following functions are invoked on the object and return a string:

  • print()
  • str()

If we have not defined the __str__, then it will call the __repr__ method. The __repr__ method returns a string that describes the pointer of the object by default (if the programmer does not define it).

How to call __str__ method

1. Default implementation

class MyClass:
    x = 0
    y = ""

    def __init__(self, anyNumber, anyString):
        self.x = anyNumber
        self.y = anyString

myObject = MyClass(12345, "Hello")

print(myObject.__str__())
print(myObject.__repr__())
print(myObject)

The above code shows an example where neither __str__ nor __repr__ are defined. Calling __str__ calls the default __repr__ method, and they all give the same output, the pointer of our object.

2. Custom __str__ method

class MyClass:
    x = 0
    y = ""

    def __init__(self, anyNumber, anyString):
        self.x = anyNumber
        self.y = anyString
    def __str__ (self):
        return 'MyClass(x=' + str(self.x) + ' ,y=' + self.y + ')'
myObject = MyClass(12345, "Hello")

print(myObject.__str__())
print(myObject)
print(str(myObject))
print(myObject.__repr__())

The code above shows the output once you have defined the __str__ method. When __str__, print(), or str() are called you will get your defined output. Make note that the __repr__ output remains the same.

3. __repr__ method defined only

class MyClass:
    x = 0
    y = ""

    def __init__(self, anyNumber, anyString):
        self.x = anyNumber
        self.y = anyString
    def __repr__ (self):
        return 'MyClass(x=' + str(self.x) + ' ,y=' + self.y + ')'
myObject = MyClass(12345, "Hello")

print(myObject.__str__())
print(myObject)
print(str(myObject))
print(myObject.__repr__())

In the first example we saw that when __str__ is not defined it automatically calls the __repr__ method. Therefore, the output of all the functions - __str__, str(), and __repr__ - are the same. Moreover, the __repr__ method does not necessarily need to return a string. In case it does not return a string, the print() statements will throw an error.

CONTRIBUTOR

Shahpar Khan

Copyright ©2022 Educative, Inc. All rights reserved

Summary: in this tutorial, you’ll learn how to use the Python __str__ method to make a string representation of a class.

Introduction to the Python __str__ method

Let’s start with the Person class:

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

Code language: Python (python)

The Person class has three instance attributes including first_name, last_name, and age.

The following creates a new instance of the Person class and display it:

person = Person('John', 'Doe', 25) print(person)

Code language: Python (python)

Output:

<__main__.Person object at 0x0000023CA16D13A0>

Code language: Python (python)

When you use the print() function to display the instance of the Person class, the print() function shows the memory address of that instance.

Sometimes, it’s useful to have a string representation of an instance of a class. To customize the string representation of a class instance, the class needs to implement the __str__ magic method.

Internally, Python will call the __str__ method automatically when an instance calls the str() method.

Note that the print() function converts all non-keyword arguments to strings by passing them to the str() before displaying the string values.

The following illustrates how to implement the __str__ method in the Person class:

class Person: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def __str__(self): return f'Person({self.first_name},{self.last_name},{self.age})'

Code language: Python (python)

And when you use the print() function to print out an instance of the Person class, Python calls the __str__ method defined in the Person class. For example:

person = Person('John', 'Doe', 25) print(person)

Code language: Python (python)

Output:

Person(John,Doe,25)

Code language: Python (python)

Summary

  • Implement the __str__ method to customize the string representation of an instance of a class.

Did you find this tutorial helpful ?

What is the purpose of str () method?

The str() function converts the specified value into a string.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

__str__ is used in to show a string representation of your object to be read easily by others. __repr__ is used to show a string representation of the object.

What is __ str __ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What does str () do in Python example?

Python str() function returns the string version of the object. Parameters: object: The object whose string representation is to be returned. encoding: Encoding of the given object.