[Tutor] class method problem

Steven D'Aprano steve at pearwood.info
Sun Sep 26 02:50:30 CEST 2010


On Sun, 26 Sep 2010 04:15:03 am Roelof Wobben wrote:
> Hello,
>
> I have this code:
>
> class zoeken() :

It is traditional to name classes with an initial capital letter, so 
Zoeken would be better.

>     pass

What is the point of the "pass" statement there? That does nothing. Why 
did you put that there?

>     def __len__(self):
>         return 0
>     def __str__(self):
>         return test2

What is test2? It doesn't exist.

>     def find(self, strng, ch, start, stop):

Count the arguments: 5, including self. Remember that number. This is 
important later on.


>         index = start
>         while index < len(strng) and index < stop:
>             if strng[index] == ch:
>                 return index
>             index += 1
>             return -1

Watch the indentation. The "return -1" is *inside* the loop.

> test = zoeken()
> test.woord = "tamara"
> test2 = zoeken.find(test, "a", 1,5)
> print test(test2)
>  
> But now I get this message :
>
> Traceback (most recent call last):
>   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20,
> in <module> test2 = zoeken.find(test, "a", 1,5)
> TypeError: find() takes exactly 5 arguments (4 given)

Right. READ THE ERROR, don't just immediately cry for help. Being a 
programmer means you must have ATTENTION TO DETAIL -- the error tells 
you *exactly* what the problem is: the find() method takes five 
arguments, *including* self. You have only given four arguments:

find method expects:
1: self
2: strng
3: ch 
4: start
5: stop

find method actually gets 
1: test
2: "a"
3: 1
4: 5
5: ??????????????


> I can do zoeken.find (test2,test, "a", 1,5) but then I get this
> message:
>
> Traceback (most recent call last):
>   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20,
> in <module> zoeken.find( test2, test, "a", 1,5)
> NameError: name 'test2' is not defined

Exactly. That's because test2 does not exist.




-- 
Steven D'Aprano


More information about the Tutor mailing list