Reputation: 1232
I am completely new to python and I have experienced, for me, strange behaviour. I have two files: foo.py and test.py
test.py:
from foo import Foo
f = Foo()
f.bar(1)
When my foo.py looks as this:
class Foo:
def bar(n):
print n
I get error message:
Traceback (most recent call last):
File "test.py", line 3, in <module>
f.bar(1)
TypeError: bar() takes exactly 1 argument (2 given)
When my foo.py looks as this:
class Foo:
def bar(x,n):
print n
I get result:
1
Why is that? Why do I need to have two params declared, even though I want to have method which takes only one? Thank you
Upvotes: 0
Views: 61
Reputation: 1163
The reason is because Python expects the first argument to be object which is calling the function. If you're familiar with C++ or Java, it's similar to the "this" keyword. Just that Python is more particular that you explicitly declare this rather than implicitly. The standard coding convention suggests that you use "self" as the first argument, but you could use any really.
In your example,
from foo import Foo
f = Foo()
f.bar(1)
When you call the function bar, which is inside the class Foo, it can be called as Foo.bar(f,n) or f.bar(n). Here, self is 'f' or referring to the current object calling the class.
I suggest having a look at Why explicit self has to stay for clearer understanding.
Upvotes: 1
Reputation: 14360
The first argument in a method is supposed to be the object on which the method is called. That is when you call f.foo(1)
it means that foo
will be called with the arguments foo(f, 1)
. Normally one calls the first argument for self
, but python doesn't care about the name, your second example the object f
will be sent via the x
parameter.
Upvotes: 5