内置str方法,一般说明类的说明,或者自己定义输出。
输出类的说明:
class strtest:
def __init__(self):
print "init: this is only test"
def __str__(self):
return "str: this is only test"
if __name__ == "__main__":
st=strtest()
print st
$./str.py
init: this is only test
str: this is only test
自己定义输出:
class A():
def __init__(self, name):
self.name = name
def __str__(self):
return "A : %s" % self.name
class B():
def __init__(self):
self.val = 10000
def __str__(self):
return str(self.val)
if __name__ == '__main__':
a = A('lichen')
print(a)
b = B()
print(b)
结果:
A : lichen
10000