Reputation: 28345
import os
import sys
class Corrector:
def correctAll(dir):
print "ok"
c = Corrector()
c.correctAll(os.getcwd())
This code is printing:
TypeError: correctAll() takes exactly 1 argument (2 given)
but AFAIK os.getcwd()
returns a single string.. what's wrong here?
Upvotes: 0
Views: 109
Reputation: 17651
Your correctAll is missing the self
parameter: All instance methods must have self
as its first argument, it means "the object itself"
In other words, c.correctAll(x)
is like Corrector.correctAll(c, x)
Python shell example
>>> class Test:
... def doSomething(s, x): print x
...
>>> Test().doSomething(1)
1
>>> Test.doSomething(Test(), 1)
1
>>> Test()
<__main__.Test instance at 0xb7793acc>
>>>
Working code:
import os
import sys
class Corrector:
def correctAll(self, dir):
print "ok"
c = Corrector()
c.correctAll(os.getcwd())
See also: http://docs.python.org/tutorial/classes.html
Upvotes: 1
Reputation: 53781
Shouldn't you define self
in the argument list as well?
class Corrector: def correctAll(self, dir): print "ok"
Maybe I'm wrong...
Upvotes: 0
Reputation: 318488
In python you must accept the instance argument - called self
- explicitely (while other languages simply provide it automagically). So your method definition must looks like def correctAll(self, dir)
.
Upvotes: 1
Reputation: 70994
You need to accept self
as an argument or use the staticmethod
decorator.
class Corrector:
def correctAll(self, dir):
print "ok"
or
class Corrector:
@staticmethod
def correctAll(dir):
print "ok"
The distinction between the two is if you want the method to have access to the instance that it's called on or not. If so, then use the first one and the the instance will be available as self
. Otherwise, you can use the second one.
Python methods work by explicitly accepting the object that they are bound to as their first argument (self
is canonical here but it can really be anything). That argument is then implicitly passed when a call occurs.
Upvotes: 4