Python 创建曲面和矩形类

Python 创建曲面和矩形类,python,python-3.x,Python,Python 3.x,我正在尝试编写一个类曲面,它将 self.rect-这是一个矩形对象 \uuuu init\uuuu(self,filename,x,y,h,w)-将文件名字符串作为参数保存到self.image实例变量中 获取x,y坐标集以及h,w,并创建存储在self.rect getRect-返回矩形对象的 我导入了文件Rectangle.py,即 class Rectangle: def __init__(self, x, y, h, w): self.x = x

我正在尝试编写一个类曲面,它将

  • self.rect
    -这是一个矩形对象
  • \uuuu init\uuuu(self,filename,x,y,h,w)
    -将
    文件名
    字符串作为参数保存到
    self.image
    实例变量中
  • 获取
    x,y
    坐标集以及
    h,w
    ,并创建存储在
    self.rect
  • getRect
    -返回矩形对象的

我导入了文件Rectangle.py,即

class Rectangle:
    def __init__(self, x, y, h, w):
        self.x = x
        self.y = y
        self.h = h
        self.w = w
    def __str__(self):
        return "(x:)"+str(self.x) + ", y=" + str(self.y) + ", width:" + str(self.w) + ", height:" + str(self.h)
但它给了我一个错误:

    import Rectangle.py
ModuleNotFoundError: No module named 'Rectangle.py'; 'Rectangle' is not a package
既然矩形有init(self,x,y,h,w),我就不必返回矩形()?

self.rect()
不是曲面的函数,您的导入语句也不正确

听起来你想要这个

from Rectangle import Rectangle

class Surface:
    def __init__(self, filename, x, y, h, w):
        self.image = filename
        self.rect = Rectangle(x, y, h, w)
    def getRect(self):
        return self.rect

然而,“getter函数”并没有在这里添加任何内容

如果您不
导入Rectangle.py
,您将
从Rectangle导入Rectangle
,这意味着“从Rectangle.py导入Rectangle类”现在人们最常见的问题是在不阅读文档的教程部分的情况下尝试Python,首先。这就是像这样的问题暴露出来的。
from Rectangle import Rectangle

class Surface:
    def __init__(self, filename, x, y, h, w):
        self.image = filename
        self.rect = Rectangle(x, y, h, w)
    def getRect(self):
        return self.rect