开发者

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.cre开发者_如何学编程ate_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?


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)


It should be:

def create_table(self, results):

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


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):


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): 


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜