class scope questions
Neil Timms
neilt at bigfoot.com
Fri Feb 9 12:52:38 EST 2001
Not a real star for this sort of thing but...
in the post.. call a is incorrect. a is a class so we don't call it but
instaniate it - that is make an object described by a ...thus.. (and we'll
call it A by convention because it is a class):
(presumes A is already imported)
myObject = A()
use __init__ and put the variables in there. They are then private (but
not totally, there is a way...) to instances of the class A. Attributes
(variables of a class instance ) are best only altered by a setter or
getter methods = encapsulation.. Now that we have loads of RAM and much
speed from the CPUs we can use these conventions for more robust and esier
to read/debug code.
so we can have:
def setDog(anObject):
self.dog = anObject
or:
def getDog():
return self.dog
or even more cunning (or not) ... the setter getter
def dog(anObject=''):
if anObject:
self.dog = anObject
return self.dog
Using the setter/getter version of above - to alter the value of dog we
would then:
myObject.dog('puppy')
# the attribute dog of myObject (of class A) now has the value of 'puppy'
to get the value of the attribute dog we would:
theValueOfDog = myObject.dog()
(sorry just back from finishing a Smalltalk exam - so I'm full of it.).
Basically we hide or variables away from direct access and only alter then
via methods definind in the class. This restricts the extent of one part
of the program interacting with others and causing unintended results
(bugs, or in MS speak features), making implementation and maintenance
easier - but making us think for the deisgn.
cheers
Neil
More information about the Python-list
mailing list