[Tutor] __init__ argument
Steven D'Aprano
steve at pearwood.info
Sat Mar 16 03:34:28 CET 2013
On 16/03/13 09:46, Joshua Wilkerson wrote:
> The program keeps telling me that the __init__ in Rock takes two arguments and only one is given. Ideas?
Yes. You need to look at the arguments required when you construct a Rock() instance, and compare it to the arguments actually given.
[snip irrelevant code]
> class Rock(games.Sprite):
> """
> A rock which falls to the ground.
> """
> image = games.load_image("rock.jpg")
> speed = 1
> def __init__(self, x, y = 90):
> """ Initiate a rock object. """
Here you define the constructor (to be precise: actually the *initialiser*) for a Rock. It takes three arguments, the magic "self" argument that Python automatically provides, x, and an optional y argument. So when you create a Rock instance, the method *requires* two arguments: self and x. Since Python provides the self, you *must* provide an x.
So let's see what you do:
> def main():
> """ Play the game. """
[...]
> the_rock = Rock()
You don't provide an x, and so Python complains that it expects two arguments but only receives one (the self argument that it provides for you).
> Traceback (most recent call last):
> File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 129, in <module>
> main()
> File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 117, in main
> the_rock = Rock()
> TypeError: __init__() takes at least 2 arguments (1 given)
Notice that the exception tells you exactly *where* the problem is, and *what* the problem is. The only thing you actually need think about about is that, being a method rather than an ordinary function, behind the scenes Python slips in a "self" argument, thus the "1 given" part.
--
Steven
More information about the Tutor
mailing list