[Tutor] OOP clarification needed

Alan Gauld alan.gauld at btinternet.com
Wed Jun 2 01:21:39 CEST 2010


"Jim Byrnes" <jf_byrnes at comcast.net> wrote

> Whenever I teach myself a new language I have great difficulty 
> understanding the nuts and bolts of it's OO implementation.

Do you understand the OO concepts OK?
Is it only the language semantics you struggle with
or the underlying OO concepts?

> some older procedural languages I always end up becoming confused by 
> the large number of built in methods.

C is one of the simplest procedural languages around
and yet it comes with a huge library of functions (several
hundred in some cases). The size of the library should be easier
to manage using OOP than with older function/procedure based
libraries, because the functions are not just logically grouped
in the documentation but in the code too.

> Case in point is this code snippet from a chapter on Tkinter.
>
> def viewer(imgdir, kind=Toplevel, cols=None):
>     """
>     make thumb links window for an image directory:
>     one thumb button per image; use kind=Tk to show
>     in main  app window, or Frame container (pack);
>     imgfile differs per loop: must save with a default;
>     photoimage objs must be saved: erased if reclaimed;
>     """
>     win = kind()
>     win.title('Viewer: ' + imgdir)
>     thumbs = makeThumbs(imgdir)
> <snip>
>
> What is the relationship between kind=Toplevel in the first line and 
> win=kind() further down.

kind is a parameter ogf the function with a default value of Toplevel.
Toplevel being a class. Recall that in Python classes are objects
too and can be assigned to variables. This is similar to Smalltalk,
Lisp, Objective C and Delphi(Object Pascal) but different to C++
and Java (actually I'm not sure about Java?).

> Isn't "kind" a variable and "kind()" a method?

No kind() is an invocation of a callable object.
In Python callables tend to be either functions
or classes or methods of objects.
In this case it is an instantiation of a class.
In C++ or Java it would look something like:

win = new kind();

Because classes can be treated as objects and passed to functions
this instantiates whatever kind of object was passed into viewer.
As the comment says this could be the top level window Tk or
a generic Frame container or the default Toplevel. So long as the
new object supports all the methods that will be invoked Python
doesn't care. This is polymorphism...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list