【问题标题】:How could i call a object from the class point so that i can use it in rectangle我怎么能从类点调用一个对象,以便我可以在矩形中使用它
【发布时间】:2020-12-07 22:04:10
【问题描述】:

我想从一个类点调用 x 和 y 点并在类矩形中实现它,这样我就可以输入 x,y,w,h 并且它会打印一个具有特定值的点 (x,y)高度和宽度,还打印一个区域。

它应该产生的一个例子是

在 (3,2) 处的矩形,高度 = 2 宽度 = 1 ,面积 = 2

但是,我在第 22 行不断收到此错误:

 __str__
    result += str(self._X)+ ',' + str(self._Y) + ')'
AttributeError: 'rectangle' object has no attribute '_X'

这是我当前的代码:

import math
import sys
import stdio

class Point(object):
     def __init__(self, x, y):
          self._X = x
          self._Y = y

class rectangle:
     def __init__(self,x,y, w, h):
        self._h = h
        self._w = w

     def area(self):
          a = self._h * self._w
          return a

     def __str__(self):
          result = 'Rectangle at('
          result += str(self._X)+ ',' + str(self._Y) + ')'
          result += ' with height = ' + str(self._h)
          result += ' width = ' + str(self._w)
          result += ' , area = ' + str(self.area())
          return result


def main():
     x = int(input(sys.argv[0]))
     y = int(input(sys.argv[0]))
     w = int(input(sys.argv[0]))
     h = int(input(sys.argv[0]))
     
     rect = rectangle(x,y,w,h)
     stdio.writeln(rect)

     
if __name__ == '__main__':
     main()



【问题讨论】:

  • 您使用术语调用变量。这并不意味着你认为它意味着什么。请停止。
  • 另外,包含合理的错误回溯做得很好。

标签: python function class rectangles


【解决方案1】:

我认为您的意思是在矩形中创建一个点:

class rectangle:
     def __init__(self,x,y, w, h):
        self.point = Point(x, y)
        self._h = h
        self._w = w

     def area(self):
          a = self._h * self._w
          return a

     def __str__(self):
          result = 'Rectangle at('
          result += str(self.point._X)+ ',' + str(self.point._Y) + ')'
          result += ' with height = ' + str(self._h)
          result += ' width = ' + str(self._w)
          result += ' , area = ' + str(self.area())
          return result

【讨论】:

    【解决方案2】:

    矩形只有属性 _h 和 _w。 self 指的是矩形对象。您需要添加缺少的属性 _x 和 _y 或使用从点继承。

    【讨论】:

      【解决方案3】:

      Rectangle 类可以继承 Point,也可以在 Rectangle 中初始化。init

      class rectangle(Point):
           def __init__(self,x,y, w, h):
              super().__init__(x,y)
              self._h = h
              self._w = w
      
           def area(self):
                a = self._h * self._w
                return a
      
           def __str__(self):
                result = 'Rectangle at('
                result += str(self._X)+ ',' + str(self._Y) + ')'
                result += ' with height = ' + str(self._h)
                result += ' width = ' + str(self._w)
                result += ' , area = ' + str(self.area())
                return result
      

      但我认为最好使用第一个答案中指定的组合

      【讨论】:

        猜你喜欢
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 2011-01-19
        • 2016-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多