我怎么能从类的角度调用一个对象,这样我就可以在矩形中使用它了



我想从类点调用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()

我想你是想在矩形中创建一个点:

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

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

Rectangle类可以从Point继承,也可以在Rectangle中初始化它初始化

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

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

相关内容

最新更新