TypeError:__str__返回非字符串

时间:2015-01-03 19:53:43

标签: python eclipse python-3.x iterator

class Course(object):
    def __init__(self,cnum,name):
        self.name = name
        self.cnum = cnum
    def __str__(self):
        return 'Course:' , self.cnum  , self.name

class AssigendCourse(Course):
    def __init__(self,Course,dept,year,semester):
        self.name = Course.name
        self.cnum = Course.cnum
        if dept == 'SE' or dept == 'CE' or dept == 'CIE' or dept == 'ME':
            self.dept = dept
        else:
            self.dept = None
        if year >= 1 and year <= 4:
            self.year = year
        else:
            self.year = None
        if semester >= 1 and semester <= 3:
            self.semester = semester
        else:
            self.semester = None
    def __str__(self):
        return 'Course: ' , self.name , self.cnum

导致此类错误

TypeError: __str__ returned non-string (type tuple)

我无法确定在__str__ func中使用什么类型的语法,以便在使用时获取对象的打印:

it = iter(db)
for i in it:
    print(i)

1 个答案:

答案 0 :(得分:8)

您的__str__方法返回元组

def __str__(self):
    return 'Course:' , self.cnum  , self.name

逗号使它成为元组。

你需要加入这些价值观;我建议使用字符串格式:

def __str__(self):
    return 'Course: {} {}'.format(self.cnum, self.name)