我有一点工作,显然改变了一些东西,因为它不再起作用。这是一个更大的代码的一部分,但我已经找出了更好的问题区域。我正在运行一个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)”而不是&lt; _main line
我知道这是一个简单的问题,我只是忽略了,我需要有人帮助指出它。这是我的代码......
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("")
我已经搜索过其他类似的问题了,似乎问题可能是某个地方的括号,但我只是没有看到它。提前感谢任何发现问题的人。
顺便说一句 - 我对此很新,所以请原谅任何礼仪/编码/短语错误答案 0 :(得分: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__