【发布时间】:2013-12-13 16:55:08
【问题描述】:
我无法让这个__str__ 工作。
我创建了一个类,
class Hangman :
然后
def __str__(self) :
return "WORD: " + self.theWord + "; you have " + \
self.numberOfLives + "lives left"
程序中有一个 init 语句和赋值,但我无法让它工作!
我能做到的唯一方法就是这样做,但使用__str__
def __str__(self) :
print("WORD: {0}; you have {1} lives left".\
format(self.theWord,self.numberOfLives))
代码:
theWord = input('Enter a word ')
numberOfLives = input('Enter a number ')
hangman = Hangman(theWord,numberOfLives)
Hangman.__str__(hangman)
输出:
>>>
Enter a word Word
Enter a number 16
>>>
使用打印方法,输出:
>>>
Enter a word word
Enter a number 16
WORD: word; you have 16 lives left
>>>
【问题讨论】:
-
定义“无法工作”
-
对不起,它只是不会像预期的那样打印
-
然后给出一个实际输出与预期输出的例子。