怎么办?__init__() 需要3个参数(但只给了1个)?

-3 投票
1 回答
1339 浏览
提问于 2025-04-18 07:59

这是我遇到的错误,还有相关的代码行。之前的帖子我很抱歉。

Traceback (most recent call last):
  File "H:\Users\Daniel\Desktop\Final Project\Gold Hunter.py", line 352, in <module>
    main()
  File "H:\Users\Daniel\Desktop\Final Project\Gold Hunter.py", line 346, in main
    score = game()
  File "H:\Users\Daniel\Desktop\Final Project\Gold Hunter.py", line 195, in game
    pirate = Pirate()
TypeError: __init__() takes exactly 3 arguments (1 given)

实际代码

  main() Line 352
  score = game() Line 346
  pirate = Pirate() Line 195

海盗构造函数 它给我报错:NameError: global name 'dx' is not defined(全局名称'dx'未定义)

class Pirate(pygame.sprite.Sprite):

    EAST = 0

    def __init__(self, screen, dx):
        self.screen = screen
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("king_pirate/running e0000.bmp")
        self.image = self.image.convert()
        tranColor = self.image.get_at((1, 1))
        self.image.set_colorkey(tranColor)
        self.rect = self.image.get_rect()
        self.rect.inflate_ip(-50, -30)
        self.rect.center = (0, random.randrange(30,450))
        self.img = []

        self.loadPics()
        self.frame = 0
        self.delay = 4
        self.pause = self.delay
        self.dx = dx

1 个回答

1

我同意Lee的看法。我们看不到class Pirate:的构造函数,但很明显你在定义__init__函数时需要传入三个参数。这三个参数是self, argument1, argument2。所以当你在第195行调用pirate = Pirate()时,实际上你需要提供两个参数(self会自动传入)。你需要给它你在构造函数中定义的argument1argument2。如果你想要更多帮助,可以把构造函数贴出来。你的第195行应该像这样pirate = Pirate(argument1, argument2)

祝好运!

撰写回答