Python 中的 __str__ 方法

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)

pok*_*oke 5

Hangman.__str__(hangman)\n
Run Code Online (Sandbox Code Playgroud)\n\n

该行将仅调用__str__方法。顺便说一句,这也是如此。这是首选方法(一般来说,don\xe2\x80\x99t 直接调用特殊方法):

\n\n
str(hangman)\n
Run Code Online (Sandbox Code Playgroud)\n\n

str__str__方法只是将对象转换为字符串,但不打印它。例如,您也可以将其记录到文件中,因此打印 \xe2\x80\x99t 总是合适的。

\n\n

相反,如果你想打印它,只需打印它:

\n\n
print(hangman)\n
Run Code Online (Sandbox Code Playgroud)\n\n

print将自动调用str()该对象,并因此使用 type\xe2\x80\x99s__str__方法将其转换为字符串。

\n