[Tutor] Accessing class attributes: use methods only?

Luke Paireepinart rabidpoobear at gmail.com
Tue Feb 13 20:49:24 CET 2007


Chris Lasher wrote:
> Is it general good practice to access and set class attributes via
> methods only, or is it okay practice to directly interact with class
> attributes? The professor in a class on Perl that I'm taking suggested
> that directly accessing and setting class attributes was a bad idea.
> Just wondering what the current preference in Python is.
>   
Python goes by the premise that you won't go and muck around in the 
class if you don't know what you're doing / need to,
but if you do need to, the programming language shouldn't restrict you 
from doing so.
That's why there's no such thing as private.
Usually if the method has underlines before its name, the programmer is 
trying to tell you you shouldn't access it unless you need to.
Otherwise, I see no problem accessing data members outside of the class.
The  main problem (that I see) lies in setting the attributes:  F.E. if 
you had an array class that had an attribute called 'used' that stored 
the # of in-use items
in most cases you wouldn't want to change this value, but let the class 
handle changing it.
I hear in my CS classes that it's bad, but I think that's partially the 
C++ mindset.
I don't see anything wrong with it.
It just may not be the easiest way to do it for certain attributes.
But if you have csomeClassInstance.objidentifier = "Some New String"
I think that makes more sense than wrapping that functionality in a method.
You probably want to wait for someone else to answer, because they'll be 
able to give you more information on whether or not it's bad.
-Luke


More information about the Tutor mailing list