0

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

KurzedMetal
13k6 gold badges42 silver badges66 bronze badges
asked Aug 26, 2015 at 12:42
6
  • Fix your indentation. Commented Aug 26, 2015 at 12:45
  • 2
    And then read some basic Python documentation, which should adequately address this question. Commented Aug 26, 2015 at 12:46
  • 4
    The first argument to an instance method is the object itself . Commented Aug 26, 2015 at 12:46
  • See the official docs: A First Look at Classes Commented Aug 26, 2015 at 12:49
  • When declaring a method, the first argument is a reference to the class instance, which is usually called self. See this Stackoverflow question. Commented Aug 26, 2015 at 12:49

2 Answers 2

5

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.

answered Aug 26, 2015 at 12:47
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Aug 26, 2015 at 12:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.