цикл for переходит в NoneType только во время оператора __str__? - PullRequest
2 голосов
/ 26 сентября 2011

Итак, я работаю в Python, пытаясь создать экземпляр ShapeSet, который содержит список Shape экземпляров, и мне нужно его распечатать список Shape экземпляров.используйте цикл for в других частях кода без ошибок.Однако, когда я пытаюсь выполнить оператор print, он выводит весь список и в конце выдает ошибку: __str__ returned non-string (type NoneType)

.список здесь.(По крайней мере, это то, что я думаю, что он делает).

Любая помощь очень ценится.

class ShapeSet:
    def __init__(self):
        """
        Initialize any needed variables
        """
        self.collect = []
        self.place = None

    def __iter__(self):
        """
        Return an iterator that allows you to iterate over the set of
        shapes, one shape at a time
        """
        self.place = 0
        return self

    def next(self):
        if self.place >= len(self.collect):
            raise StopIteration
        self.place = self.place + 1
        return self.collect[self.place-1]

    def addShape(self, sh):
        """
        Add shape sh to the set; no two shapes in the set may be
        identical
        sh: shape to be added
        """
        s_count = 0
        c_count = 0
        t_count = 0
        self.collect.append(sh)
        for i in self.collect:
            if type(sh) == Square and type(i) == Square:
                if sh.side == i.side:
                    s_count = s_count + 1
                if s_count == 2:
                    self.collect.remove(sh)
                    print('already there')
            if type(sh) == Circle and type(i) == Circle:
                if sh.radius == i.radius:
                    c_count = c_count + 1
                if c_count == 2:
                    self.collect.remove(sh)
                    print('already there')
            if type(sh) == Triangle and type(i) == Triangle:
                if sh.base == i.base and sh.height == i.height:
                    t_count = t_count + 1
                if t_count == 2:
                    self.collect.remove(sh)
                    print('already there')

    def __str__(self):
        """
        Return the string representation for a set, which consists of
        the string representation of each shape, categorized by type
        (circles, then squares, then triangles)
        """
        for i in self.collect:
            if type(i) == Square:
                print ('Square with measurements ' +  str(i.side))
            if type(i) == Circle:
                print ('Circle with measurements ' + str(i.radius))
            if type(i) == Triangle:
                print ('Triangle with measurements, base/height ' + str(i.base)+ ' ' + str(i.height))

Ответы [ 2 ]

3 голосов
/ 26 сентября 2011

Вы написали

def __str__(self):
    """
    **Return** the string representation for a set, which consists of
    the string representation of each shape, categorized by type
    (circles, then squares, then triangles)
    """

но вы ничего не return - вы просто печатаете вещи.

Поместите соответствующий __str__ метод на все ваши классы:

class Square:

    def __str__(self):
        return 'Square with measurements ' +  str(i.side)

class Circle:

    def __str__(self):
        return 'Circle with measurements ' + str(i.radius)

# and so on

и представление для вашего ShapeSet:

class ShapeSet:

    def __str__(self):
        return '\n'.join(str(x) for x in self.collect)

Теперь вы можете print(some_shapeset), а также print(some_circle).

3 голосов
/ 26 сентября 2011

Считайте строку документации в вашей функции __str__. Вы должны «вернуть строковое представление», а не print это. Поскольку в функции __str__ нет оператора return, он возвращает None, что print давит.

Вместо этого фактически return желаемая строка, и пусть внешний вызов print отображает ее:

def __str__(self):
    """
    Return the string representation for a set, which consists of
    the string representation of each shape, categorized by type
    (circles, then squares, then triangles)
    """
    strings = []
    for i in self.collect:
        if type(i) == Square:
             strings.append('Square with measurements ' +  str(i.side))
        if type(i) == Circle:
            strings.append('Circle with measurements ' + str(i.radius))
        if type(i) == Triangle:
            strings.append('Triangle with measurements, base/height ' + str(i.base)+ ' ' + str(i.height))
    return '\n'.join(strings)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...