python: 理解__str__

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

class A:

def __str__(self):

return "this is in str"

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

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

class A:

def __str__(self):

return "this is in str"

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


#!/usr/bin/env python

classstrtest:

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

从上面例子可以看出,当打印strtest的一个实例st的时候,__str__函数被调用到。

你可能感兴趣的:(python: 理解__str__)