python的特殊方法 "__str__"详解

版权声明:如需发表此文章,请附带转载标志或原地址链接,谢谢合作 https://blog.csdn.net/weixin_38091140/article/details/83375165

今日在Django的orm时用到__str__方法,现在就在这讲解一下这个方法的使用。

__str__是Django的一个内置方法。str一般是用于说明类的说明,或者定义自己想要的输出结果。

1.自定义自己想要的输出

class person(object):

    def __init__(self, id, name):
        self.id = id
        self.name = name

    def __str__(self):
        return "{}---{}".format(self.id, self.name)  # .format()格式化输出



p = person(1, 'test1') 
print(p)

输出如下:

2.用于说明类的说明

class test2(object):

    def __init__(self):
        print('this is a __init__')

    def __str__(self):
        return 'this is a __str__'

p2 = test2()
print(p2)

输出如下:

猜你喜欢

转载自blog.csdn.net/weixin_38091140/article/details/83375165