- 论坛徽章:
- 0
|
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 |
|