Creating Classes

Steve Holden steve at holdenweb.com
Fri Dec 18 16:09:28 EST 2009


seafoid wrote:
> Hey Guys,
> 
> I have started to read over classes as a brief respite from my parsing
> problem.
> 
> When a class is defined, how does the class access the data upon which the
> class should act?
> 
> Example:
> 
> class Seq:                                                                
> 
>     def __init__(self, data, alphabet = Alphabet.generic_alphabet):
>         self.data = data 
>         self.alphabet = alphabet
> 
>     def tostring(self):                                                   
>         return self.data                                                  
> 
>     def tomutable(self):
>         return MutableSeq(self.data, self.alphabet)
>     
>     def count(self, item):
>         return len([x for x in self.data if x == item])
> 
> I know what it should do, but have no idea how to feed it the data.
> 
> Methinks I need to invest in actual computing books as learning from
> biologists is hazy!
> 
> Kind regards,
> Seafoid.
> 	      

Supposing you create an instance of your Seq class

    seq = Seq("aggadgaga")

When you call (let's say) the tostring() method of the *instance* the
interpreter automatically provides that as the first (self) argument to
the method call.

So in fact

   seq.tostring()

is exactly the same as

   Seq.tostring(seq)

but considerably shorter and easier to understand. Try asking the
interpreter what Seq.tostring and seq.tostring are, and you will find
one is an
unbound method", the other is a "bound method" (which means "bound to a
given instance" - in other words, it "knows" which instance it's a
method *of*.

Does this clarify it or make it more obscure?

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list