[Tutor] Follow up to 'class data'

alan.gauld@bt.com alan.gauld@bt.com
Tue, 4 Dec 2001 10:40:23 -0000

> "Everything is an object" includes, I guess classes.

This is confusing things I agree. Its true that in Python everything is an
object, including classes. But for now forget that!

In OO terms classes define templates from which we create objects
- a better term is instances, it it disambiguates from pythons 
more general idea of objects.

> So to me, the address book is an object and can be a class?

So you could create an AddressBook class which would be a 
template from which you could create multiple instances, 
each of which would be an address book. Each address book 
would have the attributes you define in your AddressBook 
class(the methods and fields) but have their own values 
stored in those fields.  Thus your father's address book may 
hold different names to yours.

> I would have thought "address book" would be the class and 
> the means of adding, modifying, deleting data would be "methods."

Could be, and the data itself could be defined as classes
- Entries for example. Thus:

> The structure as I see it would be something like:
> class AddressBook:
>    def input:
>    def modify:
>    def delete:
>    def search:
>    def sort:
>    def output:

Is fine, and the entries could look like:

class Entry
    def input
    def edit
    def compare(Entry)

Now we can have an address book that contains different 
types of entry by subclassing Entry:

class Building(Entry)
    def input

class Person(Entry)
    def input

The AddressBoook class writes its methods to use the Entry 
methods(eg compare(Entry) would be used both in searching 
and sorting...) But we can have both types of Entry 
(Building or Person) stored and AddressBook doesn't care, 
it just sees Entries!

> class AddressBook:
>    class Input(AddressBook):
>       def inputName:
>       def inputAddress:
>       def inputPhone:

Categorically NO. Classes are not functions!
Occasionally, very occasionally, we write classes that look 
like functions but its not normal practice. Similarly its 
not usually a good idea to provide set/get methods for 
every internal attribute - a common beginners mistake.
Only expose those attributes that the outside world needs 
to see.

Classes are 'living breathing things' that  know stuff and 
how to deal with that stuff. When thinking about classes 
ask "What does Foo know? And what can Foo do with what it knows?"

This is known as Responsibility Driven Design and is fundamental 
to designing with objects. Each object has its own set of 
responsibilities, no more and no less. If you can't figure 
which existing object is responsible it probably means its time 
for a new class...

As Peter Coad says: "Objects do it to themselves"

Alan G.