Read-only attributes
Posted by gldnspud on the 2nd of November, 2007 at 12:44 pm under Uncategorized. This post has 5 comments.I just found an interesting pattern while writing a class where I wanted to expose an attribute publicly, but in a read-only manner.
Here's the skeleton version of the code:
from operator import attrgetter
class Connection(object):
def __init__(self, uri):
self._uri = uri
uri = property(attrgetter('_uri'))
Ever since discovering operator, in particular attrgetter, I've been finding more useful places to use it. It makes me feel naive now to think that I would once write the above like this:
class Connection(object):
def __init__(self, uri):
self._uri = uri
@property
def uri(self):
return self._uri
For me, the first example is more meaningful at a glance.
Submit Comment