سؤال

I had this working at one point and apparently changed something because it no longer works. This is part of a larger code but I've pulled out the trouble areas to see better. I'm running a while statement to let a user input a number to expand or shrink (if negative) a rectangle.

I'm getting the output:

How much would you like to expand or shrink r by? 3
Rectangle r expanded/shrunk =  <__main__.Rectangle object at 0x000000000345F5F8>
Would you like to try expanding or shrinking again? Y or N  

And I should be getting "Rectangle(27, 37, 106, 116) " instead of the <_main line

I know it's a simple issue that I am just overlooking and I need somebody to help point it out. Here is my code...

class Rectangle:
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    def expand(self, expand_num): # Method to expand/shrink the original rectangle
        return Rectangle(self.x - expand_num, self.y - expand_num, self.w + expand_num * 2, self.h + expand_num * 2)

r_orig = Rectangle(30,40,100,110)


try_expand = 0
while try_expand != "N" and try_expand !="n":
    input_num = input("How much would you like to expand or shrink r by? ")
    expand_num = int(input_num)
    print("Rectangle r expanded/shrunk = ", r_orig.expand(expand_num))
    try_expand = input("Would you like to try expanding or shrinking again? Y or N  ")
    print("")

I've searched other similar questions and it seems the problem is probably parenthesis somewhere but I just don't see it. Thanks in advance for anybody that finds the issue.

BTW - I'm very new to this so please forgive any etiquette/coding/phrasing mishaps

هل كانت مفيدة؟

المحلول

You should add a __repr__ method to your class. For example:

class Rectangle:
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    def expand(self, expand_num): # Method to expand/shrink the original rectangle
        return Rectangle(self.x - expand_num, self.y - expand_num, self.w + expand_num * 2, self.h + expand_num * 2)

    def __repr__(self):
        return "Rectangle("+str(self.x)+", " + str(self.y)+ ", " + str(self.w) + ", " + str(self.h) + ")"
r_orig = Rectangle(30,40,100,110)


try_expand = 0
while try_expand != "N" and try_expand !="n":
    input_num = input("How much would you like to expand or shrink r by? ")
    expand_num = int(input_num)
    print("Rectangle r expanded/shrunk = ", r_orig.expand(expand_num))
    try_expand = input("Would you like to try expanding or shrinking again? Y or N  ")
    print("")

see http://docs.python.org/2/reference/datamodel.html#object.__repr__

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top