Hi marta,
On Nov 15, 2007 9:11 PM, marta sanz <p22sacam@xxxxxx> wrote:
Hi,
I have a doubt about python and I would like to ask it to you.
It is about the use of functions -methos- of a class within other
class. I
have 2 classes in 2 separate files, in file squares.py I have the
class
Square with the methods getRect() and setRect().
Now, in other file, board.py, I have the class Board that has an
object
outskirt= Square(), can anyone tell me how do I have to use the
method
setRect ?
The code is the following:
File squares.py
class Square:
def setRect(self, x,y,width,height):
self.rect= pygame.rect(x,y,width, height)
File board.py
from squares import Square
import squares
class Board :
for i in range(42):
self.outskirt.append(squares.Square(self))
The above 2 lines are nonsensical, mainly because self only exists
inside methods (and then only if you follow the convention of naming
the first argument 'self'). using self outside of methods will not
give the desired result -- in fact it'll give an error that self
doesn't exist.
What you probably want to do, is, each time a Board is created,
initialize self.outskirt with those 42 squares. This is far closer to
achieving what you want:
class Board:
def __init__ (self):
self.outskirt = [] # remember to create the list before
appending to it :)
for i in range(42):
self.outskirt.append(squares.Square(self)) # you are calling
Square with a Board as the first argument -- is this your intent?
def squareConfiguration (self):
...
for j in range(len(self.outskirt)):
#and now is when I don't know which I have to use to do it OK :
self.outskirt[j].rect= pygame.rect ( x, y, w, h)
self.outskirt[j].setRect( x, y, w, h)
Square.setRect( self.outskirt[j], x, y, w, h)
The following is probably more correct for what you want:
def squareConfiguration (self):
...
for sq in self.outskirt: # iterate through the items in
self.outskirt rather than their indices.
sq.setRect (x,y,w,h) # where are x,y,w,h coming from? are they
calculated earlier in the function? ???