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()

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it helped a lot. Still fightin´to understand classes!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.