[Tutor] Dumb question

Grimmtooth grimmtoothtoo@yahoo.com
Sat, 19 Jan 2002 01:06:28 -0500


> I'm not a programmer, so this is a kinda dumb question. What exactly is a
> class? Why would use one? How do you define one? I've done alot
> of reading
> on Python and this whole concept escapes me.

Welcome to my world :-)

After beating my head against the wall for what seems like years (OK, it HAS
been years, but whaddya expect for a self-taught geek?) I'm starting to grok
classes and thier uses. My latest project is almost entirely classes.

Think of a class as kind of a function that can be used as a template.
Instead of executing a function, you assign an object to a class. That
object can then be manipulated, can do things, and so on without disturbing
the original. You can create multiple copies of a class, alter them, and the
original will still be pristine.

For example:

class Address:
	def __init__(self, name, street, zip=None):
		self.Name	=	name
		self.Street	=	street
		self.Zip	=	zip

	def	PrintAddr(self):
		print "%s\n%s  %s\n\n" % (name, street, zip)


(this class is probably broken but...)

Now,

	AddressBook	=	[]

	while 1:
		n, s, z = QueryForAddress() # assume an input routine here

		if n:
			AddressBook.append(Address(n,s,z))
		else:
			break

	for i in AddressBook:
		i.PrintAddr()


In the above fictitious example, the Address class contains three attributes
and two methods. Method #1 is the __init__, an internal method, which sets
up the address. method #2 prints the contents of the address object.

The program itself queries you for names and addresses. As you provide them,
the Address 'template' is filled in with the info and it is stacked into an
address book. Later on, we then assign 'i' to each address in the book and
invoke the PrintAddr method to generate a printed address book.

This is a highly simplified example, but hopefully it helps.

Hang in there, it'll come to you :-)




_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com