如何解决摆脱无
我在摆脱输出中的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())
解决方法
正如评论中指出的那样,您需要使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,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)
,
您的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
我保留了两个循环,以便您轻松看到更改,但是正如有人在评论中说的那样,可以使用乘法代替。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。