[Tutor] Another class issue
alan.gauld@bt.com
alan.gauld@bt.com
Thu, 13 May 1999 10:23:14 +0100
> Since class data members/variables can be accessed
> directly in Python i.e
> Spam.meat = "Mechanically separated chicken", thus negating
> the need for
> data access methods i.e Spam.setTypeOfMeat("Mechanically separated
> chicken"), what would be the reasoning, motivation or
> whatever to implement
> classes in Python?
To do OO programming which is about encapsulation of
data and function in a single entity. Whether you
access the data directly or via methods is somewhat
irrelevant.
One of the worst types of OO design is to implement
a class(in C++) which has a get/set pair for every
data member - this is a huge waste of effort and
misses the point of offering a behavioural
interface to the class. If the behavioral interface
is done properly there will be no need for a
programmer to access the internal data, so
whether the language permits it or not is academic.
To illustrate:
A car object has a simple interface to the driver:
turn right/left, accelerate, brake, park, switch
on/off etc. The driver can *if he wishes* do these
things by accessing the component parts of his car
(eg bypass the ignition key and hot wire it) but
he choooses not to because there is a simpler
interface provided.
Data hiding is one part of OO programming that is
heavily emphasised in C++ etc but is not universally
adopted by OO languages - many Lisp OO dialects have
no data hiding at all but support other aspects of
OO more fully than C++
OO is about how you organise programs - objects
requesting services of other objects by senbding
messages to them rather than a rigid heirarchy of
function calls. Other capabilities, like polymorphism,
either through inheritance structures or otherwise
enhance the power of that metaphor by making programs
extensible in ways that are difficult to achieve using
procedural methods/techniques.
Alan G.
As I see it (through a maybe
> narrow/imperfect view),
> the classes are more akin to a C struct with some functions/methods
> included (said methods. For exmpale, why create a class such as:
>
> class Spam:
> colour1 = "red"
> colour2 = "brown"
> def colourChange(self, colour):
> self.colour1 = colour
>
> when this would do:
>
> Spam.colour1 = "yellow"
>
> If you have followed my convoluted questioning, what I am
> really asking is
> this: why use classes in Python? What would be the purpose
> (other than a
> wrapper for a library, etc)?
>
> Ken
>