Chinaunix首页 | 论坛 | 博客
  • 博客访问: 126435
  • 博文数量: 67
  • 博客积分: 1510
  • 博客等级: 上尉
  • 技术积分: 680
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-29 11:22
文章分类

全部博文(67)

文章存档

2011年(10)

2010年(28)

2009年(29)

我的朋友
最近访客

分类: Python/Ruby

2009-10-11 20:36:36

更多见:
python的类里面可以定义__str__()函数。如果定义了这个函数,当str()这个类的对像的时候就是调用的类的__str__()函数。__str__()函数必须要返回一个字符串。
同样的__unicode__也是这个道理。
__call__()函数,如果一个类定义了一个__call__()函数,那么这个类的对象就是可调用的,调用这个对象的时候会调用这个对象里面的__call__()函数。
此外还有很多其他的函数也是这样。但不是所有的函数都可以,例如要是自定一个__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"

    def __call__(self):
         print "it is in call function"
    
         
a = AA()
a()
str(a)
b = unicode(a)
print b
Atest(a)


输出结果如下:
C:\>python test.py
it is in call function
this is a test
world
hi
Traceback (most recent call last):
  File "test.py", line 24, in
    Atest(a)
NameError: name 'Atest' is not defined
阅读(526) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~