django twentieth-the role of the special method [__str__] in python3

I. Introduction

When we create a model class in django, we often use this special method [__str__] in the model class, but people who are new to this special method certainly cannot understand what this special method can achieve.

So we must know how to use this special method [__str__].

Relevant knowledge points of special method [__str__]:

①. [__str__] is one of the special methods in python3.

②.【__str__】Special methods are generally used to return self-defined return values ​​(the return value is the description of the object by default).

③. [__str__] The data type of the return value of the special method can only be a string.

 

2. [__str__] Specific use of special methods

1. When using print to print the object generated after a class is instantiated, if there is a special method defined in the class [__str__], it is to print out such data: [__str__] the return value of the special method

1.1. First, write these code contents :

class Person:

    """ 定义一个类Person,表示一个人"""

    def __init__(self,name,weight):

        self.name = name

        self.weight = weight



    def __str__(self):

        return "我的名字叫:%s;体重是:%skg;" % (self.name,self.weight)

 

1.2. Then, execute these code contents

# 创建2个对象

xiaowang = Person("小王", 56)

xiaolei = Person("小雷", 44)

# 打印这2个对象

print(xiaowang)

print(xiaolei)

1.3. Next, look at the print log

 

2. When using print to print an object generated after a class is instantiated, if the special method in the class [__str__] is annotated, it is to print out such data: the object information of which class created the object and the Memory address in memory

detail:

①. The memory address allocated by each object is unique, so we always say that the object is unique;

②. When the program process ends, the memory address of the object generated after a class is re-instantiated is the new memory address;

As shown in the figure, comment out the string definition code and print the log to view:

3. Related learning materials

For other knowledge points about the special method [ __str__ ], you can check this article: https://www.runoob.com/note/41154

Guess you like

Origin blog.csdn.net/LYX_WIN/article/details/114574111