[Tutor] Dicts and classes [Attribute access using methods]

Sheila King sheila@thinkspot.net
Tue, 12 Mar 2002 16:09:41 -0800


On Tue, 12 Mar 2002 15:43:12 -0800 (PST), Danny Yoo
<dyoo@hkn.eecs.berkeley.edu>  wrote about Re: [Tutor] Dicts and classes
[Attribute access using methods]:

> On Tue, 12 Mar 2002, Sheila King wrote:
> 
> > > [snip]
> > >     def changename(self, name): self.name = name
> > >     def changelastname(self, name): self.lastname = name
> > > [snip]
> > >      def printname(self): print self.name
> > 
> > You don't have to write a function to change the name. You can just do
> > this:

[code snip]

> > >>> bob.areacode
> > '320'
> > >>> bob.areacode = '321'
> > >>> bob.areacode
> > '321'
> 
> At the same time, it might be useful to touch attributes only through a
> method, because that gives us the ability to do some pre-validation of the
> input.  

Good point. 

> For simple classes, like a Customer, forcing all attributes to be accessed
> through methods is a bit onerous to write.  But for more complicated
> structures, we may want to make sure that instance attributes have certain
> constraints that we can control.

Yes, in fact, for more complicated access, I usually access the class
instances via methods myself. I guess I was just looking at this simple
little tutorial-style question, and thinking in much simpler and quicker
code, but the original question certainly hints at the idea of extending it
to a much bigger application. So, your comments are very appropriate here.

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/