alinsoar
alinsoar

Reputation: 15803

error while defining a method with 1 parameter in python

I try to define the function up with 1 parameter in class X, like this:

class X:

    def __init__(self):
        self.elem=[]

    def i(self, new):
        self.elem.append(new)
        self.up(self,len(self.elem)-1)                    <= error here

    def up(self, n):
        print n

border = X()

a = [2,4,3,1]

for i in a:
    border.i (i)

The error looks like this:

$ Traceback (most recent call last):
  File "p.py", line 60, in <module>
    border.i (i)
  File "prim.py", line 50, in i
    self.up(self,len(self.elem)-1)
TypeError: up() takes exactly 2 arguments (3 given)
$ 

if I call in i like this self.up(self) , it compiles, and print n displays so:

$ <__main__.X instance at 0x7f7a7ddf0128>
<__main__.X instance at 0x7f7a7ddf0128>
<__main__.X instance at 0x7f7a7ddf0128>
<__main__.X instance at 0x7f7a7ddf0128>
$ 

Upvotes: 0

Views: 44

Answers (3)

NPE
NPE

Reputation: 500773

You don't need to pass self explicitly:

self.up(self, len(self.elem)-1)
        ^^^^^ this needs to be removed

When I make this change and run your program, I get

0
1
2
3

Upvotes: 1

Ant
Ant

Reputation: 5424

you do not have to pass self to the method. It's done by python directly

That is one of the reason we use classes and methods: you dont explicit pass the object, since it is inside a class and that particular instance is therefore used

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124000

You do not need to pass self on to up():

def i(self, new):
    self.elem.append(new)
    self.up(len(self.elem)-1)

Python does this for you; by looking up self.up, you are given a bound method, which means that Python will automatically add in self when you call up().

You were, in effect, calling up(self, self, len(self.elem)-1); three elements where only 2 were expected.

Upvotes: 2

Related Questions