·

Python的__str__()方法

Published at 2024-08-29 11:21:32Viewed 113 times
Professional article
Please reprint with source link

Python的__str__()方法

说明:本文章的Python代码测试基于Python3.x


__str__()方法的作用:

  1. 不定义__str__方法,print输出对象实例时,默认打印对象实例的内存地址
  2. 定义__str__方法,print输出对象实例时,自动调用此方法
  3. 返回值必须是字符串
  4. 在Python中,方法名形如__xxx__()的方法表示此方法具有特殊的功能,也称为魔法方法

验证

1. 不定义__str__方法,print输出对象实例时,默认打印的是对象的内存地址

# 创建学生类
class Stu():
    def __init__(self, name, age):
        self.name = name
        self.age = age

s = Stu("张三", 18)
print(s)

输出:

<__main__.Stu object at 0x000002526AF05A60>

2. 定义__str__方法,print输出对象实例时,自动调用此方法

class Stu():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return "学生" + self.name + "的年龄是" + str(self.age)

s = Stu("张三", 18)
# 打印对象实例
print(s) 

输出:

学生张三的年龄是18

3. 返回值必须是字符串

class Stu():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return self.age

s = Stu("张三", 18)
print(s)

输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      7 
      8 s = Stu("张三", 18)
----> 9 print(s)

TypeError: __str__ returned non-string (type int)

因为__str__()返回值非字符串,所以报错TypeError: __str__ returned non-string (type int)


原文链接:https://blog.csdn.net/what_how_why2020/article/details/114748495

0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

Django change an existing field to foreign key

I have a Django model that used to look like this:class Car(models.Model): manufacturer_id = models.IntegerField()There is another model called Manufacturer that the id field refers to. However, I realized that it would be useful to use Django's built-in foreign key functionality, so I changed the model to this:class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer)This change appears to work fine immediately, queries work without errors, but when I try to run migrations, Django outputs the following:- Remove field manufacturer_id from car - Add field manufacturer to carDoing this migration would clear all the existing relationships in the database, so I don't want to do that. I don't really want any migrations at all, since queries like Car.objects.get(manufacturer__name="Toyota") work fine. I would like a proper database foreign key constraint, but it's not a high priority.So my question is this: Is there a way to make a migration or something else that allows me to convert an existing field to a foreign key? I cannot use --fake since I need to reliably work across dev, prod, and my coworkers' computers.内容来源于 Stack Overflow, 遵循 CCBY-SA 4.0 许可协议进行翻译与使用。原文链接:Django change an existing field to foreign key

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved