For global variables that are mutable and public, a lower case with an underscore
should be used when they need to be protected. But these kinds of variables are not
used frequently, since the module usually provides getters and setters to work with
them when they need to be protected.
A leading underscore, in that case, can mark the variable as a private element of the package:
>>> class Connection(object):
... _connected = []
... def connect(self, user):
... self._connected.append(user)
... def _connected_people(self):
... return '\n'.join(self._connected)
... connected_people = property(_connected_people)
output:
>>> my = Connection()
>>> my.connect('Tarek')
>>> my.connect('Shannon')
>>> print my.connected_people
Tarek
Shannon
----------------
>>> class Citizen(object):
... def __init__(self):
... self._message = 'Go boys'
... def _get_message(self):
... return self._message
... kane = property(_get_message)
output:
>>> Citizen().kane
'Go boys'
--------------
No comments:
Post a Comment