This code:
class testclass:
def __init__(self,x,y):
self.x = x
self.y = y
self.test()
def test():
print('test')
if __name__ == '__main__':
x = testclass(2,3)
yields:
Error:
TypeError:test() takes no argument(1 given)
I’m calling the test function without any parameter, why does the error say that I have given one?
You call the methods as
self.test(). You should mentally translate that totest(self)to find out how the call will be “received” in the function’s definition. Your definition oftesthowever is simplydef test(), which has no place for theselfto go, so you get the error you observed.Why is this the case? Because Python can only look up attributes when specifically given an object to look in (and looking up attributes includes method calls). So in order for the method to do anything that depends on which object it was invoked on, it needs to receive that object somehow. The mechanism for receiving it is for it to be the first argument.
It is possible to tell Python that
testdoesn’t actually needselfat all, using thestaticmethoddecorator. In that case Python knows the method doesn’t needself, so it doesn’t try to add it in as the first argument. So either of the following definitions fortestwill fix your problem:OR:
Note that this is only to do with methods invoked on objects (which always looks like
some_object.some_method(...)). Normal function invocation (looking likefunction(...)) has nothing “left of the dot”, so there is noself, so it won’t be automatically passed.