joslinm
joslinm

Reputation: 8115

Python function telling me I sent two arguments when I only sent one

I'm using Google's webapp framework.

What I'm trying to do below is simply send the results of query.fetch to a function that will take the results and create a table with them.

class Utilities(): 
  def create_table(results): 
  #Create a table for the results....

variable results gets two results back from query.fetch

results = query.fetch(10) #This returns two results
util = Utilities()
util.create_table(results)

Then I get the error

util.create_table(results) TypeError: create_table() takes exactly 1 argument (2 given)

I had thought that results would automatically get passed by reference. Am I wrong?

Upvotes: 3

Views: 299

Answers (5)

Gregg Lind
Gregg Lind

Reputation: 21302

It should be:

def create_table(self, results):

Indeed, self is always passed, but the method needs to know to receive it!

Upvotes: 3

Vincenzo Pii
Vincenzo Pii

Reputation: 19855

The first argument of each python class method must be an instance of the class itself. As a convention, self is the keyword which is used to refer to the class instance. There's no reason to use a different keyword and it is strongly discouraged not to follow the self convention :). When the class method is defined, the self argument must be included, however, when the class method is used, the self argument is implicitly present.

Example:

class C:
def cMethod(self, a1, a2):
    pass
[...]

>>> cinstance = C()
>>> cinstance.cMethod(x1, x2)

I just wanted to point out this two aspects :). Bye.

Upvotes: 1

Marcus Borkenhagen
Marcus Borkenhagen

Reputation: 6656

The first argument is set implicitly by python when the method is bound to an instance. In this case util. When defining a method in a class, the first argument is usually named self and is the bound object.

class Utilities():
    def create_table(self, results):
         pass # more to come

Should work fine :)

Edit:
This also means, you can call such methods also when not bound to an instance (i.e. obj.fun()):

utils = Utilities()
Utilities.create_tables(utils, results)

Upvotes: 9

Falmarri
Falmarri

Reputation: 48587

You should read up on classes. A method of a class get's (self) sent as the first perameter.

Change it to

class Utilities(): 
    def create_table(self, results): 

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799200

The first argument passed to a method is the instance of the class. You must account for this when defining it.

def create_table(self, results):

Upvotes: 1

Related Questions