输出不是在python中打印字符串

时间:2013-12-08 21:58:23

标签: python

我制作了一个程序,但我得到的输出是

(<q3v3.Student instance at 0x023BB620>, 'is doing the following modules:', ' <q3v3.Module instance at 0x023BB670> <q3v3.Module instance at 0x023BB698>')

例如,上面的输出应该给我Alice正在做以下模块:生物学,化学

帮助

这是我的完整代码:

class Student : 
    def __init__(self,students): 
        self.students= students 
        print self.students

   #def __str__(self):  # when i used this i've got error type TypeError: __str__ returned non-string (type NoneType)
    #print str(self.students)


class Module:
    def __init__(self,modules):
        self.modules = modules
        print self.modules

    #def __str__(self):
        #print str(self.modules)


class Registrations (Student,Module):
    def __init__(self):
        self.list= []
        self.stulist = []
        self.modulist= []

    def __iter__(self):
        return iter(self.list)
    def __str__(self):
       return str(self.list)


    def add(self,students,modules):
        self.list.append((students,modules))
        #print (self.list)



    def students(self,modules):
        for i in self.list:
            if i[1] == modules:
                self.modulist.append((i[0]))
        return iter(self.modulist)


    def __str__(self):
        return str(self.students)


    def modules(self,students):
        for i in self.list:
            if i[0] == students:
                self.stulist.append((i[1]))
        return iter(self.stulist)


    def __str__(self):
        return str(self.modules)

我需要导入我的程序才能运行它:

from q3v4 import *


james = Student('james')
alice = Student('alice')
mary = Student('mary')

agm = Module('agm')
ipp = Module('ipp')

r = Registrations()
r.add(james,agm)
r.add(alice,agm)
r.add(alice,ipp)


mstr = ''
for m in map(str,r.modules(alice)):
    mstr = mstr+' '+m
print(alice, 'is doing the following modules:', mstr)
sstr = ''
for s in map(str,r.students(agm)):
   sstr = sstr+' '+s
print(agm, 'has the following students:', sstr)

print(r)

2 个答案:

答案 0 :(得分:3)

您可以在__str__课程中定义Student方法,并执行以下操作:

def __str__(self):
    return self.name # Here the string you want to print

答案 1 :(得分:0)

您使用的是Python 2吗?如果是这样,print是关键字,而不是函数。有两种方法可以解决您的问题:

  1. 撰写print foo, bar代替print(foo, bar)

    不同之处在于print(foo, bar)实际上打印出元组 (foo, bar),它使用每个元素的repr()表示,而不是{{1} }}

  2. 在文件的最顶部,写下str()。这会将from __future__ import print_function从关键字神奇地转换为函数,从而使代码按预期工作。

  3. 如果 使用Python 3,我的回答是无关紧要的。