Home > Mobile >  how can i print a pattern using __str__ in python?
how can i print a pattern using __str__ in python?

Time:04-02

I need to print a rectangle using the str method in a class

I tried writing a function that prints the rectangle and returning it from str using f string:

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

but in output I get None on the next line:

test code:

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

Output:

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

CodePudding user response:

Your pprint method does not return anything. You should create a string and return it instead of printing to stdout.

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

CodePudding user response:

You rectangle class doesn't really need the ppprint function as you can achieve your objective by overriding repr. Something like this:

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:

####
####
####
####
####
  • Related