【问题标题】:how to return a string method in a class?如何在类中返回字符串方法?
【发布时间】:2013-05-01 10:14:04
【问题描述】:

这是我在 python 中得到的一些代码,我被困在如何在 python 中的类中打印字符串方法...如果可以请帮忙...thnx 很多...

代码如下!

class Rat:
    """ A rat caught in a maze. """

    # Write your Rat methods here.
    def __init__(Rat, symbol, row, col):
        Rat.symbol = symbol
        Rat.row = row
        Rat.col = col

        num_sprouts_eaten = 0

    def set_location(Rat, row, col):

        Rat.row = row
        Rat.col = col

    def eat_sprout(Rat):
        num_sprouts_eaten += 1        

    def __str__(self):
        """ (Contact) -> str

        Return a string representation of this Rat.
        """
        result = 'To: '
        for contact in Rat.symbol:
            result = result + '{0}, '.format(Rat.symbol)

        result = result + '\nSubject: {0}'.format(Rat.row)
        result = result + '\n{0}'.format(Rat.col)
        return result
        #return '{0} {1} <{2}>'.format(Rat.symbol, 
         #   Rat.row, Rat.col)

我需要知道如何返回 Rat 的字符串表示形式!

返回老鼠的字符串表示形式,格式如下: (row, col) 处的符号吃了 num_sprouts_eaten 豆芽。

例如:'J at (4, 3) 吃了 2 个豆芽。' 不要在字符串末尾添加换行符('\n')。

那么我将如何修复最后一个方法?

  def __str__(self):
            """ (Contact) -> str

            Return a string representation of this Rat.
            """
            result = 'To: '
            for contact in Rat.symbol:
                result = result + '{0}, '.format(Rat.symbol)

            result = result + '\nSubject: {0}'.format(Rat.row)
            result = result + '\n{0}'.format(Rat.col)
            return result
            #return '{0} {1} <{2}>'.format(Rat.symbol, 
             #   Rat.row, Rat.col)

它需要打印出如下内容:'J at (4, 3) ate 2 sprouts.'但是使用上面的代码,当我输入 print(object) 时出现错误...我收到此错误:

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    print(a)
  File "C:\Users\gijoe\Downloads\a2.py", line 61, in __str__
    for contact in Rat.symbol:
AttributeError: class Rat has no attribute 'symbol'

【问题讨论】:

    标签: string class methods numbers format


    【解决方案1】:

    函数的第一个参数代表对象本身,并定义

    def __str__ (self):
    

    你称它为self。因此,为了避免AttributeError,在__str__ 函数中,您应该将Rat.symbol 替换为self.symbol

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-29
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多