Pedro Gonzalez
Pedro Gonzalez

Reputation: 1459

Python method call from class to class

I'm learning Python and I'm getting confused with syntax for calls from one class to another. I did a lot of search, but couldn't make any answer to work. I always get variations like:

TypeError: __init__() takes exactly 3 arguments (1 given)

Help much appreciated

import random
class Position(object):
    '''
    Initializes a position
    '''
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getX(self):
        return self.x

    def getY(self):
        return self.y

class RectangularRoom(object):
    '''
    Limits for valid positions
    '''
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def getRandomPosition(self):
        '''
        Return a random position
        inside the limits
        '''        
        rX = random.randrange(0, self.width)
        rY = random.randrange(0, self.height)

        pos = Position(self, rX, rY)
        # how do I instantiate Position with rX, rY?

room = RectangularRoom()
room.getRandomPosition()

Upvotes: 1

Views: 198

Answers (2)

gonz
gonz

Reputation: 5276

Maybe the answers to these previous questions help you understand why python decided to add that explicit special first parameter on methods:

The error message may be a little cryptic but once you have seen it once or twice you know what to check:

  1. Did you forgot to define a self/cls first argument on the method?
  2. Are you passing all the required method arguments? (first one doesn't count)

Those expecting/given numbers help a lot.

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 89097

You don't need to pass self - that is the newly created instance, and is automatically given by Python.

pos = Position(rX, rY)

Note that the error here is happening on this line, however:

room = RectangularRoom()

The issue on this line is you are not giving width or height.

Upvotes: 1

Related Questions