[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Doubt about using methods in python




Hello David,

El 15/11/2007, a las 15:01, David Gowers escribió:

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?



Um, I forgot writing the def __init__(self). What I want to do with that method is to create a square and append it to the list, so I think I've done it wrong while writing "self", haven't I?




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? ???

Well, they're calculated within that "for", what I wanted to ask was the right way of calling that method, that's why I didn't extend more in copying the body of that method :).

I'll leave it to you to figure out why.

I haven't proved them because I'm quite lost using python...
Thanks and sorry for my English..

Have you looked at http://wiki.python.org/moin/Languages ? You might
be able to find what you need to know written in your native language.

Thanks!