python-django-类函数__str__ 函数

Posted linux——quan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-django-类函数__str__ 函数相关的知识,希望对你有一定的参考价值。

打印一个实例化对象时,打印的其实时一个对象的地址。而通过__str__()函数就可以帮助我们打印对象中具体的属性值,或者你想得到的东西。

因为再python中调用print()打印实例化对象时会调用__str__()如果__str__()中有返回值,就会打印其中的返回值。

class ss:
    def __init__(self,age,name):
        self.age = age
        self.name = name
    def __str__(self):
        return str(self.age)+",,wozenmezhemeshuai,,"+self.name
if __name__=="__main__":
    s = ss(21,aitebao)
    print(s)

输出结果:
21,,wozenmezhemeshuai,,aitebao

 

以上是关于python-django-类函数__str__ 函数的主要内容,如果未能解决你的问题,请参考以下文章