[Tutor] Accessing class attributes: use methods only?

Kent Johnson kent37 at tds.net
Tue Feb 13 22:03:03 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.

Assuming you actually mean instance attributes, not class attributes; 
i.e. an attribute that has a value for each instance of a class, not an 
attribute that is shared by all instances...

Python practice is to use direct attribute access. If you need to do 
something special when an attribute is read or set, you can create a 
property. This allows you to define methods to be called when the 
attribute is accessed, without having to change the client code.

The use of getters and setters is popular in C++ and Java where it is 
painful to change client code from direct attribute access to indirect 
access through setters and getters. In Python there is no need for this 
as the change only affects the class itself.

Properties are a somewhat advanced feature; here is some more information:


More information about the Tutor mailing list