[Tutor] class to function

Alan Gauld alan.gauld at btinternet.com
Sun May 25 19:48:56 CEST 2014


On 25/05/14 16:39, rahmad akbar wrote:
> Hi guys
>
> i am trying to understand this code:
> http://nbviewer.ipython.org/gist/BenLangmead/6665861
>
> i understand functions quite alright . but i have no idea about
> classes yet.

Do you understand modules?
Modules contain functions and data that you can reuse
across programs. Are you comfortable with the idea of
importing and using modules?

Classes are one step on from modules.
A module can contain data but that data is restricted in
that you can only have a single instance of it. For example
if you had a module full of functions for processing a data
tree and the root was a module variable. You can load the
tree and use it just fine. But if you want to work with
more than one tree you either have to throw away (or cache)
the old tree before populating the new one or combine
both trees under a single root (which probably won't work well).

To solve that you build the module functions and data into
a Tree class. Then you can create multiple Trees each
with their own root. To do that you take each of the module
functions and put then into the class as "methods". You then
put the global root variable  into the class as instance
data. You do that by creating an __init__() method that
accepts the root data as a parameter and populates
the instance root variable (self.root).

When you create an instance of a tree you pass in the root
variable and Python "magically" calls the __init__()
method, passing your root in to it.

You probably have been doing this with things like strings
for ages. You create a string by assigning a string literal

s = 'my string'

instead of explicitly calling

s = str('my string')

But the effect is the same. You create an instance of a
string object which has methods attached, like upper(),
split() etc,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list