【问题标题】:Python error TypeError: __init__() takes exactly 2 arguments (1 given)Python 错误 TypeError: __init__() 正好需要 2 个参数(1 个给定)
【发布时间】:2014-03-29 21:14:53
【问题描述】:

在使用 Python 编程时,我遇到了需要 2 个参数但只有一个参数的错误。

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

我已经尝试添加额外的参数和其他方式,但我还没有找到让它工作的参数是我的代码如下所示的类自我参数。

    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()

【问题讨论】:

  • 首先使用GetNPC()GetNPCHandler() 有什么意义?

标签: python class oop


【解决方案1】:

您的 NPCHandler 类需要一个参数 (npcId),但是当您在 GetNPCHandler 中创建一个新对象时,您没有传递任何参数。

错误消息说您传递一个参数的原因是 self 是隐式传递的。您还需要传递第二个参数 (npcId)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2012-10-08
    • 2015-07-17
    相关资源
    最近更新 更多