"Private" Member Variables
Matteo Dell'Amico
della at toglimi.linux.it
Fri May 28 13:34:48 EDT 2004
Scott Brady Drummonds wrote:
> What are your thoughts? How much privacy should I build into my code?
> Should I be using variables beginning with "__" and accessors? Or is that
> simply not necessary (or normal) in Python code?
The motto here is "we are all consenting adults". If the class users
need to access a variable, then why not make it directly available?
If you later notice that you'd need an accessor method, since the value
of the "variable" has got to be precomputed, then use properties[1]. For
instance:
class Rectangle(object):
def __init__(self, b, h):
self.b, self.h = b, h
def get_area(self):
return self.b * self.h
area = property(get_area)
In this case the property is read-only, but you can also put a setter if
you need it.
[1] You need new-style classes for properties, so make sure you inherit
from object or one of its descendants.
--
Ciao,
Matteo
More information about the Python-list
mailing list