2014-03-03 1 views
1

У меня было это сработало в какой-то момент и, по-видимому, что-то изменило, потому что оно больше не работает. Это часть более крупного кода, но я вытащил проблемы, чтобы лучше видеть. Я запускаю оператор while, чтобы позволить пользователю вводить число, чтобы развернуть или сжать (если отрицательный) прямоугольник.Не удается найти семантический выпуск

Я получаю результат:

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 

И я должен получать "Прямоугольник (27, 37, 106, 116)" вместо < _Главных линий

Я знаю, что это просто вопрос, который я просто просматриваю, и мне нужен кто-то, чтобы помочь указать на это. Вот мой код ...

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

Я искал другие подобные вопросы, и это, кажется, проблема, вероятно, где-то скобки, но я просто не вижу. Заранее благодарим за любого, кто находит проблему.

BTW - Я очень новичок в этом, так пожалуйста, прости любой этикет/кодирования/фразировка казусы

ответ

2

Вы должны добавить метод __repr__ к классу. Например:

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

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

+0

Это сработало! СПАСИБО!!! – user3372154