for 循环仅在 __str__ 语句期间迭代到 NoneType ?

发布于 2024-12-06 05:27:49 字数 2575 浏览 1 评论 0原文

因此,我正在使用 Python 尝试创建一个包含 Shape 实例列表的 ShapeSet 实例,我需要它来打印 Shape 列表代码>实例。

我可以在代码的其他部分使用 for 循环而不会遇到错误。但是,当我尝试使用 print 语句时,它会打印出整个列表,并最终导致错误: __str__ 返回非字符串(类型为 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))

So I'm working in Python trying to create a ShapeSet instance that contains a list of Shape instances and I need it to print out the list of Shape instances.

I can use the for loop in other parts of the code without running into an error. However, when I attempt a print statement it prints out the whole list and at the end results in error:
__str__ returned non-string (type NoneType)

I don't understand why it fails to understand to stop at the end of the list here. (At least that's what I think it's doing).

Any help is greatly appreciated.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痞味浪人 2024-12-13 05:27:49

阅读 __str__ 函数中的文档字符串。您应该“返回字符串表示形式”而不是打印它。由于 __str__ 函数中没有 return 语句,因此它返回 None,导致 print 窒息。

相反,实际上返回所需的字符串,并让外部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)

Read the docstring in your __str__ function. You're suppose to "return the string representation" not print it. Since there is no return statement in the __str__ function, it returns None, which print chokes on.

Instead, actually return the desired string, and let the external print call display it:

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)
云仙小弟 2024-12-13 05:27:49

你写了

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

但你不返回任何东西 - 你只是打印东西。

在所有类上放置适当的 __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) 以及 >打印(some_circle)

You wrote

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

but you don't return anything - you just print stuff.

Put a appropriate __str__ method on all your classes:

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

and a representation for your ShapeSet:

class ShapeSet:

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

Now you can print(some_shapeset) as well as print(some_circle).

緦唸λ蓇 2024-12-13 05:27:49

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

在你的情况下:

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

You could also do whatever you like within the str method, itterate, print outputs, more logic, etc, as long as at the end, you return a string i.e. return "" just to satisfy the requirement.

In Your case:

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 ""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文