accessing class data members

Skip Montanaro skip at
Tue Jul 3 14:34:45 EDT 2001

    Curtis> In many OO languages, and theory, it is often the case that when
    Curtis> you want to know the value of some data member, that a function
    Curtis> is written to return that value.  However, in Python it seems
    Curtis> that people just access the data member directly.
    Curtis> Which is better?

As usual, it depends.  By not providing set/get methods you are promoting
the data member into the external API of the class.  Depending on how stable
your class is, that can be good or bad.  The example I remember best is a 2D
point class.  Internally you can represent a point using either cartesian
(x, y) or polar (r, theta) coordinates (or other representations, I'm sure).
Obviously, if you expose x and y data members and then decide later that a
polar coordinate representation would be better, you have more work to do to
preserve your API.

But, you can use getattr/setattr to provide both interfaces without using
set/get methods:

    class Point:
        def __init__(self, r, theta):
	    self.r = r
	    self.theta = theta

        def __getattr__(self, name):
	    if name == "x":
	        x,y = self.compute_cartesian()
		return x

Exposing data members isn't necessarily good or bad.

Skip Montanaro (skip at

More information about the Python-list mailing list