[Tutor] Re: Newbie OOP Question.(diff between function, module and class)
Skip Montanaro
skip@pobox.com
Mon, 10 Jun 2002 12:26:52 -0500
>> * A class associates a chunk of data with a set of functions which
>> operate on that data. The first argument to each function in a
>> class (typically called a "method" in Python) is a reference to the
>> data stored in that instance of the class. For example:
>>
>> 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)
>>
SA> So the "def __init__" is a function in the class and is assigning
SA> the variables x and y as attributes of the class, correct? If so,
SA> are the variables x and y supplied outside of the class (I guess
SA> this would be global)?
__init__ is the constructor for the class. It's called for you when you
instantiate the class appropriately. You create an instance of the class
like so:
mypoint = Point(1,0)
>> * A module is an object that partitions the namespace in a hierarchy.
SA> A module is more or less, in very general terms, a package of
SA> classes and/or functions that are then imported into the __main__
SA> program, correct?
Even more generally, a package of objects. Conceptually, it's no different
than how you'd carve up the namespace you live in outside of programming.
Ambiguous names need qualification. If you wife says, "Honey, bring me up a
can of paint from the basement for the blue wall", and you have several
rooms painted in several shades of blue, you'd need a qualifier to decide
what room the paint was for.
SA> One last question, sorry if this is very basic but I feel these
SA> terms need better definitions for newbies like me (the only other
SA> languages I have experience with are Qbasic and HTML) what is a
SA> namespae? Is that analagous to pwd of the program? For instance, if
SA> the program is currently in one are of the script doing work, would
SA> that be considered the namespace?
Yes, it is more or less like the filesystem hierarchy. In the current
directory, a reference to "blue.txt" would reference a file in the current
directory. One significant difference is that Python's module/package
system doesn't have a syntax for referring to the current module's parent
(no "..").
--
Skip Montanaro (skip@pobox.com - http://www.mojam.com/)
Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html