如何在类中返回一个字符串方法?

时间:2013-05-01 10:14:05

标签: string class methods numbers format

这里是我在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的字符串表示形式!

以这种格式返回rat的字符串表示形式: (row,col)的符号吃了num_sprouts_eaten sprouts。

例如:'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)吃了2个豆芽。'但是使用上面的代码,当我输入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'

1 个答案:

答案 0 :(得分:0)

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

def __str__ (self):

您已将其称为self。因此,为避免AttributeError__str__函数中,您应该替换Rat.symbol中的self.symbol