关于__str__的介绍

在python语言里,__str__一般是格式是这样的。

class A:

    def __str__(self):

        return "this is in str"

事实上,__str__是被print函数调用的,一般都是return一个什么东西。这个东西应该是以字符串的形式表现的。如果不是要用str()函数转换。当你打印一个类的时候,那么print首先调用的就是类里面的定义的__str__,比如:str.py

 

如下脚本:

class  ybl():
   name='yubenliu'
   def __str__(self):
       return  self.name
t=ybl()
print t
print t.__str__()
    
print type(t)

返回的结果是:

 

return 返回的只可以是字符串如果是其他的类型就会报错

 

在PYTHON中默认的类都__STR__这个属性如

 

 

用于print调用如:

>>> t={}

>>> t['1'] = "hello"

>>> t['2'] = "world"
>>> t   #等于 print t
{'1': 'hello', '2': 'world'}
>>> t.__str__()
"{'1': 'hello', '2': 'world'}"
大家可以看到一个字典,print t 和 t.__str__()是一样的。只不过__str__()将字典内容以字符串形式输出

posted @ 2016-09-18 15:40  下丶雨天  阅读(310)  评论(0编辑  收藏  举报