类声明和类实例上的操作

2024-05-23 22:45:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在跟随《如何像计算机科学家一样思考》一书学习python 我在理解类和对象章节时遇到了一些问题。在

其中的一个练习是写一个名为moveRect的函数,它接受一个矩形和两个名为dx&dy的参数。它应该通过将dx添加到角点的x坐标和将dy添加到角点的y坐标来更改矩形的位置。在

现在,我不太确定我写的代码是否正确。 那么,让我告诉你我想做什么 你能告诉我我做得对吗?在

首先我创建了一个类矩形 然后我创建了它的一个实例 并输入了诸如 坐标x和y的值 以及矩形的宽度和高度。在

我之前的代码是:

class Rectangle:
    pass
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120

def moveRect(Rectangle,dx,dy):
    Rectangle.x=Rectangle.x + dx
    Rectangle.y=Rectangle.y + dy

dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")

moveRect(Rectangle,dx,dy)

但是当我运行这段代码时,它给了我一个属性错误 and:类矩形没有属性x

因此,我将以下行移到moveRect函数中

^{pr2}$

因此,代码变成:

class Rectangle:
    pass


def moveRect(Rectangle,dx,dy):
    Rectangle.x=Rectangle.x + dx
    Rectangle.y=Rectangle.y + dy
    rect=Rectangle()
    rect.x=3.0
    rect.y=4.0
    rect.width=50
    rect.height=120


dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")

moveRect(Rectangle,dx,dy)

但是,这个代码还是给了我一个错误。 那么,这个代码到底有什么问题? 现在,我觉得我写这段代码好像是用试错法写的, 当我看到一个错误的时候就改变了。我想好好理解 怎么会这样工作。所以,请解释一下。在

《如何像一个计算机科学家一样思考》一书在第12章中没有介绍init,因此我需要在不使用init的情况下这样做。在


Tags: 函数代码rectinputrawvalue计算机错误
3条回答

在第一个示例中,传递了作为参数,而不是您创建的实例。因为类Rectangle中没有self.x,因此引发了错误。在

只需将函数放入类中:

class Rectangle:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def moveRect(self, dx, dy):
        self.x += dx
        self.y += dy

rect = Rectangle(3.0, 4.0, 50, 120)

dx = raw_input("enter dx value:")
dy = raw_input("enter dy value:")
rect.moveRect(float(dx), float(dy))

在不使事情过于复杂的情况下,使代码正常工作所需的就是进行更改

moveRect(Rectangle,dx,dy)

^{pr2}$

(您需要确保将raw_input中的每个字符串转换为一个数字。在moveRect中,将Rectangle.x添加到dx中,这两个值的类型必须相同,否则将得到TypeError。)

鉴于你正在阅读的book要求你完成这一exercise的知识,你已经正确地完成了这个问题。

正如其他人所说,这不是一种解决问题的方法。如果您继续阅读,您将看到如何将函数作为类定义的一部分(作为一个方法);将数据和对该数据进行操作的函数捆绑在一个单元中更有意义。在

必须指定要在类声明中访问和使用的成员和方法。在类内部,您当前正在处理的实例被名称self引用(请参阅下面的链接!)公司名称:

class Rectangle:
   def __init__(self):
       self.x = 0
       self.y = 0
       self.width = 50
       self.height = 30

   # may I recommend to make the moveRect function
   # a method of Rectangle, like so:
   def move(self, dx, dy):
       self.x += dx
       self.y += dy

然后实例化类并使用返回的对象:

^{pr2}$

希望有帮助。在

阅读:http://www.diveintopython.net/object_oriented_framework/defining_classes.html

相关问题 更多 >