1

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()
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
Pedro Gonzalez
  • 1,429
  • 2
  • 19
  • 30

2 Answers2

1

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.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
0

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.

Community
  • 1
  • 1
gonz
  • 5,226
  • 5
  • 39
  • 54