473,378 Members | 1,605 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

best practices for making read-only attributes of an object

I've set up an object and would like to make certain
attributes read-only (or at least enforce it without doing
extra work, as per name-mangling or the like). Ideally, the
property would be set in the __init__, and then not be
allowed to change.

The best solution I've been able to come up with is
something of the form:
class Foo:
def __init__(self, name, value):
self.__dict__['_name'] = name
self.value = value
def __getattr__(self, attr):
name = "_%s" % attr
if name in self.__dict__: return self.__dict__[name]
raise AttributeError, attr
def __setattr__(self, attr, value):
if attr == 'value':
self.__dict__['value'] = value
else:
raise AttributeError, attr

Is there a better ("more pythonic") way to do this?
Particularly if it plays well with sub-classing Foo.

Thanks,

-tim

Mar 15 '06 #1
2 1210
Tim Chase wrote:
I've set up an object and would like to make certain attributes
read-only (or at least enforce it without doing extra work, as per
name-mangling or the like). Ideally, the property would be set in the
__init__, and then not be allowed to change.

The best solution I've been able to come up with is something of the form:
class Foo: old-style classes are deprecated, please use new-style classes:
class Foo(object): def __init__(self, name, value):
self.__dict__['_name'] = name
self.value = value
def __getattr__(self, attr):
name = "_%s" % attr
if name in self.__dict__: return self.__dict__[name]
raise AttributeError, attr
def __setattr__(self, attr, value):
if attr == 'value':
self.__dict__['value'] = value
else:
raise AttributeError, attr

Is there a better ("more pythonic") way to do this?
One usually uses properties withour setter:

class Parrot(object):
def __init__(self, is_dead):
self._is_dead = is_dead

is_dead = property(fget=lambda self: self._is_dead)

p = Parrot(False)
print p, p.is_dead
Particularly if it
plays well with sub-classing Foo.


class DeadBlueParrot(Parrot):
def __init__(self):
self._color = "Blue"
Parrot.__init__(self, True)

color = property(fget=lambda self: self._color)

d = DeadBlueParrot()
print d, d.color, d.is_dead

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Mar 15 '06 #2
bruno at modulix wrote:
Tim Chase wrote:

class Foo:


old-style classes are deprecated, please use new-style classes:
class Foo(object):


This should be re-phrased to 'Use new-style classes, or else!'

py> class Foo:
.... def __init__(self, color):
.... self._color = color
.... color = property(fget=lambda self: self._color)
....
py> p = Foo('red')
py> p.color
'red'
py> p.color = 'green' # shouldn't be able to do this
py> p.color
'green'
py>
py> class Parrot(object):
.... def __init__(self, color):
.... self._color = color
.... color = property(fget=lambda self: self._color)
....
py> p = Parrot('orange')
py> p.color
'orange'
py> p.color = 'pink'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Mar 15 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

136
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their...
13
by: john doe | last post by:
A quick question, about so-called 'best practices', I'm interested in which of A/B of the two examples people would choose, and why. public enum MyEnum { Option1 = 0, Option2 = 1, Option3 =...
10
by: jojobar | last post by:
Hello, I am trying to use vs.net 2005 to migrate a project originally in vs.net 2003. I started with creation of a "web site", and then created folders for each component of the site. I read...
3
by: newtophp2000 | last post by:
I have several forms that display information from the database after users log in. I would like the column titles to be sortable so that when the user clicks on a column heading, the data...
26
by: puzzlecracker | last post by:
It'd be interesting to compare the learning practices of c++ practitioners. I'll start with mine The C++ Programming Language C++ Primer Effective C++ More Effective C++ Effective STL The...
1
by: maciek | last post by:
Hi, I was wondering if anyone could suggest me a book/article/tutorial on Exception Handling in multi tier Windows Apps. What are the best practices/ways to implement EH in multi tier...
4
by: Ned Balzer | last post by:
Hi all, I am pretty new to asp.net; I've done lots of classic asp, but am just beginning to get my mind wrapped around .net. What I'd like to do is include some code that tests if a user is...
3
by: John Dalberg | last post by:
I am looking for an ASP.NET application on CodePlex which exemplifies best practices for the following: - Use of interfaces - Seperation of the UI, business and data tiers - Data Tier that uses...
13
by: vizcayno | last post by:
Hello: Need your help in the "correct" definition of the next function. If necessary, I would like to know about a web site or documentation that tells me about best practices in defining...
9
by: Bob Alston | last post by:
I have an application with about 30 users, most of whom use the application on laptops that they take with them. The system is split into FE and BE. The BE on each laptop is a replica. The...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.