TypeError:Python认为我传递了一个函数2参数,但我只传递了它1

时间:2010-12-21 12:49:02

标签: python exception parameters arguments

我在Seattle Repy中处理某些内容,这是Python的一个受限制的子集。无论如何,我想实现我自己的队列,它来自list

class Queue(list):
    job_count = 0

    def __init__(self):
        list.__init__(self)

    def appendleft(item):
        item.creation_time = getruntime()
        item.current_count = self.job_count
        self.insert(0, item)

    def pop():
        item = self.pop()
        item.pop_time = getruntime()
        return item

现在我在我的主服务器中调用它,在那里我使用自己的Job类将作业传递给队列:

mycontext['queue'] = Queue()
# ...
job = Job(str(ip), message)
mycontext['queue'].appendleft(job)

最后一行引发以下异常:

  

异常(类型为'exceptions.TypeError'):appendleft()只取1个参数(给定2个)

我对Python比较陌生,所以任何人都可以向我解释为什么当显然只有一个时,我会认为我给了appendleft()两个参数?

3 个答案:

答案 0 :(得分:6)

您必须在每个函数定义中输入自引用:

def appendleft(self, item):

答案 1 :(得分:6)

Python自动传递SELF(即当前对象)作为第一个参数,因此您需要将appendleft的函数定义更改为:

def appendleft(self, item):

对于类中的其他函数定义也是如此。它们都需要SELF作为函数定义中的第一个参数,所以:

def pop():

需要:

def pop(self):

答案 2 :(得分:3)

Python将对象本身作为其方法的第一个参数传递。您需要修改类方法以采用强制性的第一个参数,通常是一个名为self的强大约定。

阅读本文 - http://docs.python.org/tutorial/classes.html