[Tutor] Another class issue

Joseph J. Strout joe@strout.net
Wed, 12 May 1999 08:20:33 -0700


At 6:20 AM -0700 05/12/99, K P wrote:

>what would be the reasoning, motivation or whatever to implement
>classes in Python?

The benefits of object-oriented programming are numerous!  Information
hiding is only one; and there are ways to do this in Python as well (it's
just that by default, all data members are publicly accessible, which is
convenient for beginners and for rapid prototyping).

Basically, a class keeps your data and your functions together
("encapsulation").  You don't have to worry about accidentally passing a
Foo structure to a function that's expecting a Bar; you just to
myObject.Func() and it executes the right thing.

Even better, is that one class can "derive" (or "inherit") from another (or
several others), extending their functionality by adding new methods, or
changing only the methods that need to be changed.  (These are the
properties of inheritance and polymorphism.)  It's hard to explain briefly
why this is so amazingly powerful, but you'll discover it as you get more
experience programming.

>why create a class such as:
>
>class Spam:
>	colour1 = "red"
>	colour2 = "brown"
>	def colourChange(self, colour):
>		self.colour1 = colour

Why indeed?  You have no instance variables here, but only class variables.
I use class variables very rarely, and if you had a class with *only* class
variables, like the above, there would be not much point in it at all.  The
sensible class would be this:

class Spam:
	def __init__(self):
		colour1 = "red"
		colour2 = "brown"
		num = 5

Then, as you say, the colourChange method is not really needed.  If this is
all you need, then fine, the Spam class is basically a data structure.  But
often you want these things to actually do something.  E.g.:

	def print(self):
		print "spam "*num

Now you can do mySpam = Spam(), then mySpam.print() to see what happens.
Now let's explore inheritance.  Suppose you want a modified version of Spam
for special cases, like this:

class SpamWithBeans(Spam):
	def print(self):
		print "spam "*(num-1),"baked beans and spam"

Now, if you do mySpam = SpamWithBeans(), mySpam.print() will do something
slightly different than it does for regular Spam.  See what I mean?

Cheers,
-- Joe
,------------------------------------------------------------------.
|    Joseph J. Strout           Biocomputing -- The Salk Institute |
|    joe@strout.net             http://www.strout.net              |
`------------------------------------------------------------------'