簡體   English   中英

如何在 python 中使用 __str__ 打印圖案?

[英]how can i print a pattern using __str__ in python?

我需要在 class 中使用str方法打印一個矩形

我嘗試編寫一個 function 打印矩形並使用 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()}"

但在 output 下一行我得到 None :

測試代碼:

my_rectangle.width = 10
my_rectangle.height = 3
print(my_rectangle)

Output:

##########
##########
##########
None

您的pprint方法不返回任何內容。 您應該創建一個字符串並將其返回,而不是打印到標准輸出。

def pprint(self):
    height = self.__height
    width = self.__width
    return '\n'.join('#' * width for _ in range(height))

您的矩形 class 並不真正需要 ppprint function,因為您可以通過覆蓋 repr 來實現您的目標。 是這樣的:

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

Output:

####
####
####
####
####

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM