Skip to main content
 首页 » 编程设计

Python:TypeError __init__() 正好需要 5 个参数(给定 4 个)

2025年01月19日9lonelyxmas

我刚开始使用 Python,遇到了一个我无法解释的问题。希望你能帮忙。

def createGrid(x,y,N): 
    nDictionary={} 
    for i in range(N+1): 
        node=Node(i,x/N*i,y/N*i) 
        nDictionary[node.nlabel] = node  
 
    return nDictionary 
 
class Node(object): 
    def __init__(self,nlabel,x,y,z): 
        self.nlabel = nlabel 
        self.coordinates = x,y,z 

现在

nDictionary={} 
node=Node(0,0,0,0) 
nDictionary[node.nlabel]=node 

工作但调用方法

createGrid(10,10,10) 

导致下面的错误

TypeError: __init__() takes exactly 5 arguments (4 given) 

我真的不知道为什么。

请您参考如下方法:

我想问题出在这一行:

node=Node(i,x/N*i,y/N*i) 

我猜你想在这里有 4 个参数,而不是 3 个。

(错误消息有点困惑的原因(说你应该给出 5、4)是因为对 self 参数的特殊处理 - 参见 an external explanation)