[Tutor] FW: Can this be done easly

Andre Engels andreengels at gmail.com
Sun Sep 19 20:16:15 CEST 2010


On Sun, Sep 19, 2010 at 7:02 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
>
>
>
> ----------------------------------------
>> From: rwobben at hotmail.com
>> To: __peter__ at web.de
>> Subject: RE: [Tutor] Can this be done easly
>> Date: Sun, 19 Sep 2010 17:01:22 +0000
>>
>>
>>
>>
>> ----------------------------------------
>>> To: tutor at python.org
>>> From: __peter__ at web.de
>>> Date: Sun, 19 Sep 2010 18:27:54 +0200
>>> Subject: Re: [Tutor] Can this be done easly
>>>
>>> Roelof Wobben wrote:
>>>
>>>>> Hint: why does this work:
>>>>>
>>>>>> def __init__(self, x=0, y=0):
>>>>>
>>>>> ...while this doesnt:
>>>>>
>>>>>> def _init_(self, base_point, width=0, length=0):
>>>>>
>>>>> Peter
>>>
>>>> Maybe because base_point has no value ?
>>>
>>> No. One __init__ has two underscores (correct) on each side, the other
>>> _init_ only one (wrong).
>>>
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> Hello,
>
> Everybody thanks.
>
> For this exercise :
>
> 3.Write a function named move_rect that takes a Rectangle and two parameters named dx and dy. It should change the location of the rectangle by adding dx to the x coordinate of corner and adding dy to the y coordinate of corner.
>
> Is this one of the possible solutions :
>
>
> class Point:
>    def __init__(self, x=0, y=0):
>        self.x = x
>        self.y = y
>
> class Rectangle(object):
>    def __init__(self, base_point, width=0, length=0):
>        self.base_point = base_point
>        self.width = width
>        self.length = length
>
> def moverect(rectangle, dx, dy):
>    rechthoek.base_point.y += dy
>    rechthoek.base_point.x +=dx
>    return rechthoek
>
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
> test = moverect (Rectangle, 4,3)
> print rechthoek.base_point.x


This test happens to work, but your program is incorrect.

In moverect, you should work with the local variable (rectangle), not
with the global one (rechthoek), because it should be possible to call
it for any Rectangle, not just with the Rectangle that happens to be
called rechthoek. Then, when you call it, you should specify the
Rectangle that you call it for, so

test = moverect (Rectangle, 4, 3)

should be

test = moverect(rechthoek, 4, 3)

Furthermore, you do not use test (which will be null anyway), so you
can shorten this to

moverect(rechthoek, 4, 3)

-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list