TypeError:__ init __()得到了一个意外的关键字参数'size

时间:2016-08-22 21:49:30

标签: python

如何解决这个意外的关键字参数'size'?

   Traceback (most recent call last):
      File "H:\Documents\Astro game\astro games6.py", line 73, in <module>
        main()
      File "H:\Documents\Astro game\astro games6.py", line 61, in main
        new_asteroid = Asteroid(x = x, y = y,size = size)
    TypeError: __init__() got an unexpected keyword argument 'size'

完整代码:

import random
from superwires import games

games.init(screen_width = 640, screen_height = 480, fps = 50)

class Asteroid(games.Sprite):
    """ An asteroid wich floats across the screen"""
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    images = {SMALL : games.load_image("asteroid_small.bmp"),
              MEDIUM : games.load_image("asteroid_med.bmp"),
              LARGE : games.load_image("asteroid_big.bmp")}
    speed = 2

    def _init_(self, x, y, size):
        """Initialize asteroid sprite"""
        super(Asteroid, self)._init_(
            image = Asteroid.images[size],
            x = x, y = y,
            dx = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size,
            dy = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size)

        self.size = size


    def update (self):
        """ Warp around screen"""
        if self.top>games.screen.height:
            self.bottom = 0

        if self.bottom < 0:
            self.top=games.screen.height

        if self.left > games.screen.width:
            self.right = 0

        if self.left < 0:
            self.left = games.screen.width

class Ship(games.Sprite):
    """The player's ship"""
    image = games.load_image("ship.bmp")
    ROTATION_STEP = 3

    def update(self):
        if games.keyboard.is_pressed(games.K_LEFT):
            self.angle -= Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.angle += Ship.ROTATION_STEP


def main():
    nebula_image = games.load_image("nebula.jpg")
    games.screen.background = nebula_image

    for i in range(8):
        x = random.randrange(games.screen.width)
        y = random.randrange(games.screen.height)
        size = random.choice([Asteroid.SMALL, Asteroid.MEDIUM, Asteroid.LARGE])
        new_asteroid = Asteroid(x = x, y = y,size = size)
        games.screen.add(new_asteroid)


    the_ship = Ship(image = Ship.image,
                    x = games.screen.width/2,
                    y = games.screen.height/2)

    games.screen.add(the_ship)

    games.screen.mainloop()

main()

我尝试删除size参数,但它在代码中导致了更多错误。我们还尝试将大小标记更改为其他内容以查看是否有帮助,但它也无效。所以我需要做的就是让这段代码能够运行。我正在为学校的一个班级项目而努力。英语不是我的第一语言所以我有一个同学写这篇文章。

谢谢。

2 个答案:

答案 0 :(得分:0)

您的Asteroid类定义_init_而不是__init__。对于Python魔术方法,你需要两个下划线。

答案 1 :(得分:-2)

删除代码中的size参数。

注意:Python模块名称不应该有空格:您将无法在另一个模块中导入它。