输出不是用python打印字符串

2024-06-11 20:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个程序,但是我得到的结果是

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

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

帮助

这是我的完整代码:

^{2}$

我需要导入程序才能运行到以下位置:

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)

Tags: theinstanceaddmodulesstudentatfollowingmodule
2条回答

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

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

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

  1. print foo, bar而不是print(foo, bar)。在

    区别在于print(foo, bar)实际上是打印出元组(foo, bar),它使用每个元素的repr()表示,而不是它的str()

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

如果你在使用python3,我的答案就无关紧要了。在

相关问题 更多 >