[Tutor] Another Class question.

Magnus Lycka magnus@thinkware.se
Thu, 15 Aug 2002 01:24:09 +0200


At 17:44 2002-08-14 -0500, SA wrote:
>Hi Everyone-
>
>While we are the subject of classes, here is one more question for you (at
>least I hope it is one more...):
>
>If I have the following class-
>
>Class Fud:
>     def __init__(self, text)
>         self.text =3D text    # does this create an instance?

No, you create an instance when you write

x =3D Fud('dfgdfg')

__init__() is run when you create an instance. It doesn't
create the instance. If you don't want anything particular
to happen when you create the instance, you can skip __init__.

>     def search(self, start, end):
>         tags =3D r'''%s.+%s''' % (start, end)
>     def extract(self):
>         self.text =3D re.findall(tags, self.text)
>
>First off, is this written correctly? If not where did I goof? Secondly,
>tags in the extract funtion should be the same as the final tags in the
>search function. So should I be using tags, self.tags, or search.tags in=
 the
>extract function in order to pass along the correct value to that function?
>So my main question deals with namespace defining in this class.

The first parameter to a method, conventionally called self, is
the instance object. If x is an instance of Fud, x.extract() is
just a short form of Fud.extract(x).

So if the value of "tags" is to live beyond the execution of
the search method, you need "self.tags =3D r'''...", and to access
it in extract you need "re.findall(self.tags ..."

A plain "tags" would be a local variable that is garbage collected
as soon as i goes out of scope (end of method). Search.tags would
not help. "Tags" need to be an attribute of the particular instance
object, not the method.


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se