开发者

TypeError: Python thinks that I passed a function 2 arguments but I only passed it 1

开发者 https://www.devze.com 2023-01-31 09:45 出处:网络
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

class Queue(list):
    job_count = 0

    def __i开发者_开发技巧nit__(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

Now I call this in my main server, where I use my own Job class to pass Jobs to the Queue:

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

The last line raises the following exception:

Exception (with type 'exceptions.TypeError'): appendleft() takes exactly 1 argument (2 given)

I'm relatively new to Python, so could anyone explain to me why it would think that I gave appendleft() two arguments when there obviously was only one?


You must enter the self reference in each function definition:

def appendleft(self, item):


Python automatically passes SELF (ie the current object) as the first argument, so you'd need to change the function definition for appendleft to:

def appendleft(self, item):

This is also true for other function definitions within a class. They all require SELF as the first parameter in the function definition, so:

def pop():

would need to be:

def pop(self):


Python passes the object itself as the first argument to it's methods. You need to modify your class methods to take the mandatory first argument, conventionally (a strong convention that is) named self.

Read this - http://docs.python.org/tutorial/classes.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号