Python error TypeError: __init__() takes exactly 2

2019-02-27 17:50发布

问题:

WHilst programming in Python i have come across this error about needing 2 arguments and only having one.

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

I have tried adding extra arguments and other ways but i have not found away to get it working the argument is the class self argument my code is shown below.

    import sys, pygame

pygame.init()

size = width, height = 750, 500
backgroundColour = 23, 195, 74

screen = pygame.display.set_mode((size), 0, 32)

class NPC():
    npcList = []

    def GetNPCList(self):
        listNPC = []
        for i in range(0, self.npcList):
            test = self.npcList[i].id
            listNPC.append(test)
        print(listNPC)  


def GetNPC():
    return NPC()

class NPCHandler(object):
    def __init__(self, npcId):
        self.id = id

    def newNPC(self, npcId):
        return NPCHandler(npcId)

    def addNPC(self, n = NPC):
        return n.npcList.append(n)

def GetNPCHandler():
    return NPCHandler()

def main():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                sys.exit()

        for i in range(0, 5):
            GetNPCHandler().addNPC(GetNPCHandler().newNPC(1))

        GetNPC().GetNPCList()

        screen.fill(backgroundColour)

        #pygame.draw.circle(screen, (0, 0, 0), (100, 100), 10, 0)

        pygame.display.update()

if __name__ == "__main__":
    main()

回答1:

Your NPCHandler class requires an argument (npcId), but when you create a new object inside GetNPCHandler, you are passing no arguments.

The reason the error message says you are passing one argument is that self is passed implicitly. You need to also pass the second argument (npcId).



标签: python class oop