【问题标题】:Can't Find Semantic Issue找不到语义问题
【发布时间】:2014-04-03 20:45:11
【问题描述】:

我曾经有过这个工作,但显然改变了一些东西,因为它不再工作了。这是较大代码的一部分,但我已将问题区域拉出以便看得更清楚。我正在运行一个 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  

我应该得到“Rectangle(27, 37, 106, 116) ”而不是 <_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("")

我搜索了其他类似的问题,似乎问题可能出在某处的括号中,但我只是没有看到。提前感谢任何发现问题的人。

顺便说一句 - 我对此很陌生,所以请原谅任何礼仪/编码/措辞上的失误

【问题讨论】:

    标签: python semantics parentheses


    【解决方案1】:

    你应该在你的类中添加一个__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__

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多