Jam*_*lly 3 python string methods
我无法让它发挥__str__作用。我创建了一个类,
class Hangman :
Run Code Online (Sandbox Code Playgroud)
进而
def __str__(self) :
return "WORD: " + self.theWord + "; you have " + \
self.numberOfLives + "lives left"
Run Code Online (Sandbox Code Playgroud)
程序中有一个 init 语句和赋值,但我无法让它工作!我能做到的唯一方法就是这样做,但肯定使用有什么意义__str__
def __str__(self) :
print("WORD: {0}; you have {1} lives left".\
format(self.theWord,self.numberOfLives))
Run Code Online (Sandbox Code Playgroud)
代码:
theWord = input('Enter a word ')
numberOfLives = input('Enter a number ')
hangman = Hangman(theWord,numberOfLives)
Hangman.__str__(hangman)
Run Code Online (Sandbox Code Playgroud)
输出:
>>>
Enter a word Word
Enter a number 16
>>>
Run Code Online (Sandbox Code Playgroud)
使用print方法,输出:
>>>
Enter a word word
Enter a number 16
WORD: word; you have 16 lives left
>>>
Run Code Online (Sandbox Code Playgroud)
Hangman.__str__(hangman)\nRun Code Online (Sandbox Code Playgroud)\n\n该行将仅调用该__str__方法。顺便说一句,这也是如此。这是首选方法(一般来说,don\xe2\x80\x99t 直接调用特殊方法):
str(hangman)\nRun Code Online (Sandbox Code Playgroud)\n\nstr该__str__方法只是将对象转换为字符串,但不打印它。例如,您也可以将其记录到文件中,因此打印 \xe2\x80\x99t 总是合适的。
相反,如果你想打印它,只需打印它:
\n\nprint(hangman)\nRun Code Online (Sandbox Code Playgroud)\n\nprint将自动调用str()该对象,并因此使用 type\xe2\x80\x99s__str__方法将其转换为字符串。
| 归档时间: |
|
| 查看次数: |
6839 次 |
| 最近记录: |