【问题标题】:__str__ method in PythonPython 中的 __str__ 方法
【发布时间】: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
>>> 

【问题讨论】:

标签: python string methods


【解决方案1】:
Hangman.__str__(hangman)

这一行将调用 __str__ 方法。顺便说一句,这也是如此。这是首选的方法(一般情况下,不要直接调用特殊方法):

str(hangman)

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

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

print(hangman)

print 将自动在对象上调用str(),因此使用该类型的__str__ 方法将其转换为字符串。

【讨论】:

  • 啊啊啊!不敢相信这很容易。非常感谢!
【解决方案2】:

Hangman.__str__(hangman) 不是打印hangman 的字符串表示的命令,它是一个表达式,计算结果为hangman 的字符串表示。

如果您在交互式提示中手动键入,您将获得打印的表达式的值,因为交互式提示这样做是为了方便。在脚本中(或在您调用的函数中)包含该行不会打印任何内容 - 您需要使用 print(hangman) 实际告诉 python 打印它。

【讨论】:

    【解决方案3】:

    就像这篇文章所说: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!
    

    引用

    回顾一下:当你告诉 Python “打印 b”时,Python 调用 str(b) 来 得到 b 的字符串表示。如果 b 的类有一个 __str__ 方法,str(b) 成为对 b.__str__() 的调用。这将返回字符串 打印。

    【讨论】:

      【解决方案4】:

      此代码有效:

      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)
      

      输出:

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

      【讨论】:

        猜你喜欢
        • 2020-09-23
        • 1970-01-01
        • 2021-11-04
        • 2018-05-27
        • 2015-04-18
        • 2014-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多