摆脱无

时间:2020-08-21 09:20:17

标签: python-3.x class

我在摆脱输出中的None时遇到问题。我尝试分配变量,但仍然徒劳。非常感谢您的帮助。

P.S-执行必须为print(rect1.get_picture())。 它不能只是rect1.getpicture()。 这是要求的一部分

class Rectangle:
    def __init__(self,width,height):
       self.width = width
       self.height=height

    def get_picture(self):
        def draw():
            for j in range(self.height):
                for i in range(self.width):
                    print("*", end="")
                print()

        if self.height>50 or self.width>50:
            return ("Too big for picture")

        else:
            return draw()
rect1 =Rectangle(width=5,height=5)
print(rect1.get_picture())

2 个答案:

答案 0 :(得分:1)

正如评论中指出的那样,您需要使draw函数实际上返回可以打印的内容。

例如:

class Rectangle:
    def __init__(self, width, height):
       self.width = width
       self.height= height

    def get_picture(self):
        def draw():
            return "\n".join("*"*self.width for _ in range(self.height))

        if self.height > 50 or self.width > 50:
            return ("Too big for picture")
        else:
            return draw()

rect1 = Rectangle(width=7, height=5)
print(rect1.get_picture())

产生

*******
*******
*******
*******
*******

为了使内容更OO,我让Rectangle自己打印,并遵守Python的打印协议

class Rectangle:
    def __init__(self,width,height):
       self.width = width
       self.height= height

    def __str__(self):
        if self.height > 50 or self.width > 50:
            return ("Picture too big for printing")
        return "\n".join("*"*self.width for _ in range(self.height))

rect1 =Rectangle(width=7, height=5)
print(rect1)

答案 1 :(得分:0)

您的draw函数应该返回一个字符串而不是打印它。请注意,您始终可以打印结果。

def draw():
    for j in range(self.height):
        for i in range(self.width):
            print("*", end="")
        print()

更改为

def draw():
    rectangle = ""
    for j in range(self.height):
        for i in range(self.width):
            rectangle += "*"
        rectangle += "\n"
    return rectangle

我保留了两个循环,以便您轻松看到更改,但是正如有人在评论中说的那样,可以使用乘法代替。

相关问题