我曾经有过这个工作,显然改变了一些东西,因为它不再工作。 这是一个更大的代码的一部分,但我已经拉出了麻烦区域以更好地看到。 我正在运行一个 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)"而不是<_main行
我知道这是一个简单的问题,我只是忽略了,我需要有人帮助指出它。 这是我的代码...
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("")
我已经搜索了其他类似的问题,似乎问题可能是某处的括号,但我只是没有看到它。 提前感谢任何发现问题的人。
顺便说一句 - 我对此很陌生,所以请原谅任何礼仪/编码/措辞错误
你应该向类添加一个__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__