免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3589 | 回复: 0

Python的str()和__str__ [复制链接]

论坛徽章:
0
发表于 2009-10-11 20:36 |显示全部楼层

                python的类里面可以定义__str__()函数。如果定义了这个函数,当str()这个类的对像的时候就是调用的类的__str__()函数。__str__()函数必须要返回一个字符串。
同样的__unicode__也是这个道理。此外还有很多其他的函数也是这样。但不是所有的函数都可以,例如要是自定一个__Atest__()就不行。代码如下:
               
               
                #coding:utf-8
class AA():
    def __Atest__(self):
        print "hello"
        
    def __unicode__(self):
        print "world"
        return u"hi"
        
    def __str__(self):
        print "this is a test"
        return "this is a test"
        
   
         
a = AA()
str(a)
b = unicode(a)
print b
Atest(a)
输入结构如下:
C:\>python test.py
this is a test
world
hi
Traceback (most recent call last):
  File "test.py", line 21, in
    Atest(a)
NameError: name 'Atest' is not defined
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/103690/showart_2067837.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP