Hướng dẫn __str__ method in python
Show
Nội dung chính
The need for __str__ method:The The
If we have not defined the How to call __str__ method1. Default implementationclass 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 2. Custom __str__ methodclass 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 3. __repr__ method defined onlyclass 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 CONTRIBUTOR Shahpar Khan Copyright ©2022 Educative, Inc. All rights reserved Summary: in this tutorial, you’ll learn how to use the Python Introduction to the Python __str__ methodLet’s start with the
The The following creates a new instance of the
Output:
When you use the 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 Internally, Python will call the Note that the The following illustrates how to implement the
And
when you use the
Output:
Summary
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. |