[Tutor] Re: Newbie OOP Question.(diff between function, module and class)

Alexandre Ratti alex@gabuzomeu.net
Mon, 10 Jun 2002 19:06:36 +0200


At 11:41 10/06/2002 -0400, you wrote:
>Date: Mon, 10 Jun 2002 10:39:37 -0500
>From: SA <sarmstrong13@mac.com>
>Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module 
>and class)

> >   import math
> >   class Point:
> >       def __init__(self, x, y):
> >           self.x = x
> >           self.y = y
> >
> >       def polar(self):
> >           return math.sqrt(self.x**2+self.y**2), math.atan2(self.y, 
> self.x)
>
>So the "def __init__" is a function in the class and is assigning the
>variables x and y as attributes of the class, correct?

Yes. A function used in a class is usually called a "method".

>If so, are the variables x and y supplied outside of the class

Correct. They are parameters that are passed when the method (__init__()) 
is called.

>(I guess this would be global)?

Within __init__(), x and y are local variables. Hence they disappear when 
the method exits. That's why they are reassigned to self.x and self.y. 
self.x and self.y are attributes that survive as long as the class instance.

>A module is more or less, in very general terms, a package of classes 
>and/or functions that are then imported into the __main__ program, correct?

Yes, sounds reasonable.

>One last question, sorry if this is very basic but I feel these terms need
>better definitions for newbies like me (the only other languages I have
>experience with are Qbasic and HTML) what is a namespae? Is that analagous 
>to pwd of the program?

As I understand it, namespaces are related to scope of variables. 
Namespaces are similar to nested containers that holds variables. When you 
use a variable, Python looks up its value in the nearest, smallest 
namespace (i.e. local). If it cannot find it, it will look a bit farther 
(eg. the namespace of the current class instance). Still missing? Then it 
looks in the global namespace. Still missing? Python looks in the built-in 
namespace. What, still missing? Python gives up and raise an error.

I think namespaces can be pictured as small boxes in larger boxes. Values 
are searched in smaller boxes first. Also, the smaller the box, the shorter 
the variable lifetime.

>See everything I read explains these terms in definitions that are readibly
>understandable by people with programming experience. I kind of need a
>"layman's" terms tutorial because I'm so new to programming.

Here is a small test to try and make it more concrete:

##
globalFoo = "I am a global variable."

class Test:
     classFoo = "I am a class variable."

     def __init__(self):
         self.instanceFoo = "I am an instance variable."
         localFoo = "I am a local variable."
         print globalFoo
         print self.classFoo
         print self.instanceFoo
         print localFoo

if __name__ == "__main__":
     t = Test()
##


Cheers.

Alexandre