laroy
laroy

Reputation: 153

Understanding Python __init__

I have a class called Game in which I have

class Game:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

and below everything I have

def main():
    g = Game()
    while True:
        g.__init__(5,10,4)

when running my program I get the following error:

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

I suppose my understanding of __init__ must be lacking, but I don't understand why this happens. Can init not take parameters?

Upvotes: 0

Views: 52

Answers (1)

Prune
Prune

Reputation: 77857

You don't call __init__ explicitly from the main program; this is called automatically when you create an instance (object) of type Game. What you need is much simpler:

def main():
    g = Game(5, 10, 4)

The four arguments are self and the three integers; the error comes from the original formation, where you gave it only self.

Also, note that your last two lines would have been an infinite loop to initialize the object. This would make your game very boring, as it would never finish initializing. :-)

Upvotes: 1

Related Questions