简体   繁体   English

Python中的__str__方法

[英]__str__ method in Python

I can't manage to get this __str__ to work. 我无法使这个__str__正常工作。 I created a class, 我创建了一个课程

class Hangman : 

and then 接着

def __str__(self) : 
return "WORD: " + self.theWord + "; you have " + \
self.numberOfLives + "lives left"

there's an init statement and assignment in the program but I can't get the thing to work! 程序中有一个init语句和赋值,但我无法正常工作! the only way I can do it is by doing this, but surely what's the point of using __str__ 我唯一可以做到的方法就是这样做,但是肯定使用__str__什么__str__

def __str__(self) :
    print("WORD: {0}; you have {1} lives left".\
    format(self.theWord,self.numberOfLives))

Code: 码:

theWord = input('Enter a word ')
numberOfLives = input('Enter a number ')
hangman = Hangman(theWord,numberOfLives)
Hangman.__str__(hangman)

Output: 输出:

>>> 
Enter a word Word
Enter a number 16
>>> 

using the print method, output: 使用打印方法,输出:

>>> 
Enter a word word
Enter a number 16
WORD: word; you have 16 lives left
>>> 
Hangman.__str__(hangman)

This line will just call the __str__ method. 该行将仅调用 __str__方法。 So does this btw. 顺便说一句。 which is the preferred way to do it (in general, don't call special methods directly): 这是首选的方法(通常,不要直接调用特殊方法):

str(hangman)

str and the __str__ method are just there to convert the object into a string, but not to print it. str__str__方法仅用于对象转换为字符串,而不是打印它。 For example you could just as well log it to a file, so printing wouldn't always be appropriate. 例如,您也可以将其记录到文件中,因此打印并不总是合适的。

Instead, if you want to print it, just print it: 相反,如果要打印,只需打印:

print(hangman)

print will automatically call str() on the object and as such use the type's __str__ method to convert it to a string. print将自动在对象上调用str() ,因此使用该类型的__str__方法将其转换为字符串。

Like this post says: https://mail.python.org/pipermail/tutor/2004-September/031726.html 像这样的帖子说: https : //mail.python.org/pipermail/tutor/2004-September/031726.html

 >>> class A:
...   pass
...
 >>> a=A()
 >>> print a
<__main__.A instance at 0x007CF9E0>

If the class defines a __str__ method, Python will call it when you call 
str() or print:
 >>> class B:
...   def __str__(self):
...     return "I'm a B!"
...
 >>> b=B()
 >>> print b
I'm a B!

Quoting 引用

To recap: when you tell Python to "print b", Python calls str(b) to get the string representation of b. 回顾一下:当您告诉Python“打印b”时,Python调用str(b)来获取b的字符串表示形式。 If the class of b has a __str__ method, str(b) becomes a call to b.__str__(). 如果b的类具有__str__方法,则str(b)成为对b .__ str __()的调用。 This returns the string to print. 这将返回要打印的字符串。

Hangman.__str__(hangman) isn't a command to print the string representation of hangman , it's an expression that evaluates to the string representation of hangman . Hangman.__str__(hangman)不是打印hangman字符串表示形式的命令,它是一个表达式,其计算结果为hangman的字符串表示形式。

If you type that manually at the interactive prompt, you'll get the value of the expression printed, because the interactive prompt does that as a convenience. 如果您在交互式提示符下手动键入该命令,则将获得打印表达式的值,因为交互式提示符这样做是为了方便。 Having that line in a script (or in a function you call) will not print anything - you need to actually tell python to print it, with print(hangman) . 在脚本(或您调用的函数)中包含该行将不会打印任何内容-您实际上需要使用print(hangman)告诉python打印它。

This code works: 此代码有效:

class Hangman(object):

    def __init__(self, theWord, numberOfLives):
        self.theWord = theWord
        self.numberOfLives = numberOfLives

    def __str__(self) :
        return "WORD: " + self.theWord + "; you have " + \
               self.numberOfLives + " lives left"

if __name__ == '__main__':
    theWord = input('Enter a word ')
    numberOfLives = input('Enter a number ')
    hangman = Hangman(theWord,numberOfLives)
    print(hangman)

Output: 输出:

>>> 
Enter a word word
Enter a number 16
WORD: word; you have 16 lives left

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM