I have a file notifications.py and comments.py. notifications has a class GetNotifications with a function getNotifs(arg1, arg2). I'd like to call this method in my comments.py, so I do:
from notifications import GetNotifications
Then I create an instance of the class:
getNotifsInstance = GetNotifications()
Then I try to call getNotifs:
notifsDictionary = getNotifsInstance.getNotifs(arg1, arg2)
However, I'm getting the error:
TypeError: getNotifs() takes at most 2 arguments (3 given)
Why is it saying I'm giving it 3 arguments when I'm only giving it 2?
-
1When you call a method of an instance it always passes itself as the first parameter.jamylak– jamylak2012年04月17日 15:08:10 +00:00Commented Apr 17, 2012 at 15:08
4 Answers 4
You're giving it three arguments: when you call an instance method, the instance is passed as the first parameter. You should add an argument self as the first parameter of the method.
Comments
You've most probably forgotten about the self argument when declaring getNotifs():
def getNotifs(self, arg1, arg2):
...
Comments
Why is it saying I'm giving it 3 arguments when I'm only giving it 2?
Simply because you are accessing the function getNotifys as a member function of object getNotifsInstance. The first argument to any member function is (self) the object reference itself.
Comments
In the class you can define three kinds of methods:
class A(object):
def instance_method(*args):
print '%d arguments given' % len(args)
@classmethod
def class_method(*args):
print '%d arguments given' % len(args)
@staticmethod
def static_method(*args):
print '%d arguments given' % len(args)
And when you invoke them on the instance, you will get additional argument passed to instance method (which will be instance itself) and class method (which will be a class of the instance):
>>> a = A()
>>> a.instance_method('a', 'b')
3 arguments given
>>> a.class_method('a', 'b')
3 arguments given
>>> a.static_method('a', 'b')
2 arguments given
In your case it is probably self (the instance itself), although results would be similar if you would decorate your method with classmethod decorator (in that case you would get a class passed as the first argument).