【问题标题】:for loop iterates into a NoneType only during a __str__ statement?for 循环仅在 __str__ 语句期间迭代到 NoneType ?
【发布时间】:2011-11-24 20:48:04
【问题描述】:

所以我正在使用 Python 尝试创建一个包含 Shape 实例列表的 ShapeSet 实例,我需要它来打印出 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))

【问题讨论】:

    标签: python iterator


    【解决方案1】:

    阅读__str__ 函数中的文档字符串。您应该“返回字符串表示”而不是 print 它。由于__str__ 函数中没有return 语句,它返回Noneprint 阻塞。

    相反,实际上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)
    

    【讨论】:

    • 谢谢!我把它想象成一个只打印出我的 shapeset 的函数,而不是 str
    【解决方案2】:

    你写的

    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)

    【讨论】:

    • 谢谢!还有非常好的代码,我想知道如何让 ShapeSet 函数返回正确的信息。我会研究你的代码。再次感谢您!
    【解决方案3】:

    你也可以在 str 方法中做任何你喜欢的事情,迭代,打印输出,更多逻辑等等,只要在最后,你返回一个字符串,即返回 "" 只是为了满足要求。

    在你的情况下:

    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))
        return ""
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2015-08-04
      • 2016-01-19
      • 1970-01-01
      • 2020-01-15
      • 2020-09-20
      • 1970-01-01
      相关资源
      最近更新 更多