[Tutor] [LONG] help on self

Tom Jenkins TomJenkins@zentuit.com
Tue, 13 Apr 1999 12:40:02 -0400


Hello Arne,
I've snipped your message down to what I consider the essentials...

> As far as I know it's a referecne to the calling object.
Yes, it is a reference to the calling object.  But Self has to be an 
instance of the class.

Looking at your code I see that in the Token class, the 'action' 
parameter references a function.  Further down in the code, where the 
Token instance is created, an Iteration instance's parseHeader method 
(or function) is passed to the Token constructor.

What this means is that the Token instance (t) has a method (or 
function) called Action that points to a specific Iteration instance's (i) 
parseHeader method.  So in your call to t.action gets sent to 
i.parseHeader.  But the Iteration instance (i) doesn't have a string 
attribute... t does.

I don't feel I have a grasp of your problem domain to offer help in how to 
restructure.  I just hope that the above makes sense.  If it doesn't, yell 
and I'll give it another try.

> 
> class Token:
>     
>     def __init__(self, token, action):
>         self.token = compile(token)
>         self.action = action # reference to a function
>         self.m = None # regex match object
>         self.string = None # the string where 'token' matches
> 
> class Parser:
> 
>     def __init__(self, f):
>         self.f = f
>         self.cont = compile('\S+')

> class Iteration(Parser):
> 
>     def parseIteration(self):
>         print 'parsing iterations ...'
>         self.tokens = [ Token('^Searching\.*done$', self.parseHeader) ]
>         t = self.searchToken()
> 	# here's a problem:
>         # 't' is a 'Token' object so I assume 't'
> 	# provides everything of the 'Token' class
>         t.action()
>         
>     def parseHeader(self):
>         print 'parsing header ...'
> 	# now we'll get an error, because self doesn't know anything
> 	# about the attribute 'string' - but why? This function was called
> 	# by an 'Token' object/instance!
> 	print self.string

> ### Testing ...
> ###
> 
> f = IO('/v8/tmp/MG001.blast')
> i = Iteration(f)
> i.parseIteration()
> 
> -------
> running the above programm results in
> 
> parsing iterations ...
> parsing header ...
> Traceback (innermost last):
>   File "./Blast.py", line 130, in ?
>     i.parseIteration()
>   File "./Blast.py", line 109, in parseIteration
>     t.action()
>   File "./Blast.py", line 113, in parseHeader
>     print self.string
> AttributeError: string
> 
> 
> Can anybody help with that strange behaviour? I think it's a 'self'
> problem, so maybe you can teach me how to understand (my)'self'?
> 
> 	Thanks very much,
> 
> 	Arne
> 

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Tom Jenkins                    DevIS (http://www.devis.com)
"In a world without fences, who needs Gates?"