accessing class data members
skip at pobox.com
Tue Jul 3 20:34:45 CEST 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
def __init__(self, r, theta):
self.r = r
self.theta = theta
def __getattr__(self, name):
if name == "x":
x,y = self.compute_cartesian()
Exposing data members isn't necessarily good or bad.
Skip Montanaro (skip at pobox.com)
More information about the Python-list