如何在 python 中使用 __str__ 打印图案?
how can i print a pattern using __str__ in python?
我需要在 class
中使用 str 方法打印一个矩形
我尝试编写一个函数来打印矩形并使用 f 字符串从 str 返回它:
def pprint(self):
"""prints a rectangle using '#'"""
for height in range(self.__height):
for width in range(self.__width):
print('#', end='')
print()
def __str__(self):
"""prints a rectangle using '#'"""
return f"{self.pprint()}"
但在输出中我在下一行得到 None:
测试代码:
my_rectangle.width = 10
my_rectangle.height = 3
print(my_rectangle)
输出:
##########
##########
##########
None
您的 pprint
方法没有 return 任何东西。您应该创建一个字符串并 return 它而不是打印到标准输出。
def pprint(self):
height = self.__height
width = self.__width
return '\n'.join('#' * width for _ in range(height))
您的矩形 class 并不真正需要 ppprint 函数,因为您可以通过覆盖 repr 来实现您的 objective。像这样:
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def __repr__(self):
return '\n'.join('#' * self.width for _ in range(self.height))
print(Rectangle(5, 4))
输出:
####
####
####
####
####
我需要在 class
中使用 str 方法打印一个矩形我尝试编写一个函数来打印矩形并使用 f 字符串从 str 返回它:
def pprint(self):
"""prints a rectangle using '#'"""
for height in range(self.__height):
for width in range(self.__width):
print('#', end='')
print()
def __str__(self):
"""prints a rectangle using '#'"""
return f"{self.pprint()}"
但在输出中我在下一行得到 None:
测试代码:
my_rectangle.width = 10
my_rectangle.height = 3
print(my_rectangle)
输出:
##########
##########
##########
None
您的 pprint
方法没有 return 任何东西。您应该创建一个字符串并 return 它而不是打印到标准输出。
def pprint(self):
height = self.__height
width = self.__width
return '\n'.join('#' * width for _ in range(height))
您的矩形 class 并不真正需要 ppprint 函数,因为您可以通过覆盖 repr 来实现您的 objective。像这样:
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def __repr__(self):
return '\n'.join('#' * self.width for _ in range(self.height))
print(Rectangle(5, 4))
输出:
####
####
####
####
####