__str__被print函数调用,目的是打印类的内容到屏幕上

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#__str__被print函数调用,目的是打印类的内容到屏幕上



class APIError():
    def __init__(self, error_code, request):
        self.error_code = error_code
        self.request = request

    def __str__(self):
        #一般都是return
        return 'APIError: %s, \nrequest: %s' % (self.error_code, self.request)


#
error=APIError('100','this is a error')
print error
print type(error)
#__str__其实和str功能基本一致,只是str用于单纯的字符串中,而__str__通常在类中使用,当打印一个类时,print首先调用类里面定义的__str__

'''
APIError: 100, 
request: this is a error
<type 'instance'>
'''

 

posted @ 2015-10-15 16:54  Xiao|Deng  阅读(456)  评论(0编辑  收藏  举报