[Tutor] class method problem

Dave Angel davea at ieee.org
Mon Sep 27 14:33:25 CEST 2010


  On 2:59 PM, Roelof Wobben wrote:
>
> Hello,
>
> Fine that you are in a arque
> But can we come back to my problem.
>
> How can I take care that test2 can be initialized.
>
> Roelof
>
You had this code, and got the following error:

class zoeken() :
     pass
     def __len__(self):
         return 0
     def __str__(self):
         return test2
     def find(self, strng, ch, start, stop):
         index = start
         while index<  len(strng) and index<  stop:
             if strng[index] == ch:
                 return index
             index += 1
             return -1


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)


The immediate answer is that
   1) you are calling the find method with the class as the first 
argument, while it was declared with 'self'.
   2) you never pass a string to be searched, so there's nothing useful 
to be passed to strng.

It's the second problem that causes the error,  but the first one is 
tied with it.  You can fix the immediate syntax error by passing the 
string explicitly.

test2 = test.find("tamara", "a", 1, 5)

The real problem though is one of design, or intent.  You're assigning 
that "tamara" to an attribute of a particular instance of zoeken().  So 
did you mean that find() would look there for it?  If that were the 
case, the find declaration should change to:


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

and naturally, the reference to strng[index]   should change to  
self.woord[index]

There are several things wrong with the find() method, and with the 
__str__() method, but the first question that needs answering is What 
does a zoeken (please capitalize it, to follow Python conventions) 
object represent?  What are its data attributes going to mean?  Since 
it's not English, I don't get a clue from the name, but normally I'd get 
one from the __init__() method, which you omitted.  My convention is to 
initialize all attributes in the __init__() method, even if they're not 
always used.  But if that's undesirable for some reason, then at least 
comment on them there.

DaveA


More information about the Tutor mailing list