【问题标题】:Why does this error say I'm giving the function two arguments?为什么这个错误说我给函数两个参数?
【发布时间】:2015-07-24 21:39:20
【问题描述】:

我定义了一个图形类,它具有获取节点名称并将名称和节点添加到字典的功能。当我运行程序时,我在底部收到错误消息。为什么它认为我给它两个参数?

class Graph:

    def __init__(self):
        self.node_list = {}
        self.number = 0

    def node(node_name):
        if node_name in self.node_list.keys:
            return node_list[node_name]
        else:
            node_list[node_name] = Node()
    ...

def PrefixTrieConstruction(patterns):
    trie = Graph()
    trie.node('root')

for pattern in patterns:
    currentNode = trie.node('root')
    for symbol in pattern:
        for daughter in currentNode.daughters:
            if daughter.label == symbol:
                currentNode = daughter
                break
        else:
            node_name = Trie.name_node()
            Trie.node(node_name)
            Trie.edge(currentNode, node_name, symbol)
            currentNode = node_name
return Trie



Traceback (most recent call last):
  File "PythonProject2.3.py", line 168, in <module>
    main()
  File "PythonProject2.3.py", line 163, in main
    TrieMatching(text, PrefixTrieConstruction(patterns))
  File "PythonProject2.3.py", line 68, in PrefixTrieConstruction
    trie.node('root')
TypeError: node() takes 1 positional argument but 2 were given

【问题讨论】:

    标签: python


    【解决方案1】:

    你不见了self:

    def node(self,node_name):
    

    self 指的是您正在调用该方法的实例,因此您已经在传递该实例,因此传递 'root' 显然会给您看到您看到的错误。

    trie.node('root') 基本上是在做Graph.node(trie,"root") 所以你将两个参数传递给一个需要一个参数的方法,你的方法中的node_name 被解释为实例所以'root' 是一个额外的参数,除非你是使用静态或类方法时,方法的第一个 arg 应始终为 self,它可以是任何名称,但按照惯例,几乎每个 Python 程序员都使用 self 来引用实例。

    difference-between-class-and-instance-methods

    what-is-the-difference-between-staticmethod-and-classmethod-in-python

    what-is-the-purpose-of-self-in-python

    【讨论】:

    • 好的,所以所有类方法都必须有'self',但是init没有?
    • @jukhamil,这取决于,静态方法不需要 self,但在基本级别上,您应该始终使用 self,而 init 也需要 self。
    • 我添加了一些与不同类型的方法相关的链接,这是一个广泛的主题,cmets 无法涵盖。
    【解决方案2】:

    这很简单! 函数node 只接受一个参数,但位于一个类中。给定隐式类实例和您的参数,这是 2 个参数。要修复它,您可以将函数编辑为

         def node(self,node_name):
    

    【讨论】:

    • 您先生,拯救了我的一天!
    【解决方案3】:

    在 python 中,方法的第一个参数始终是调用该方法的对象。这个变量按惯例称为self,但没有规定必须如此。所以当你写的时候:

    def node(node_name):
    

    node_name 被解释为“self”变量,函数的预期用法是:

    trie.node() #within this call, trie is bound to node_name
    

    所以当你写的时候:

    trie.node('root')
    

    trie 绑定到node_name,而'root' 是一个额外的参数,会导致错误。

    要获得您的预期行为,只需声明 self 变量:

    def node(self, node_name):
    

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 2022-01-05
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 2022-08-12
      相关资源
      最近更新 更多