0

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

代码如下!

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 的字符串表示!

返回老鼠的字符串表示形式,格式如下:symbol at (row, col) ate num_sproouts_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) 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'
4

1 回答 1

0

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

def __str__ (self):

你已经调用它了self。因此,为避免AttributeError, 在__str__函数内部,您应该替换Rat.symbolself.symbol.

于 2013-05-01T10:19:24.507 回答