Custom Search

Sunday, March 13, 2011

python how create read-only Instance attributes examples

python examples how create read-only Instance attributes

class Test(object):

def __init__(self):
self._year = 2011

def get_year(self):
return self._year

#property() only works with new-style classes correctly,
#(classe which are inherited from 'object')
year = property(get_year)

t = Test()
print "------t.year--------", t.year
t.year = 2012
print "------t.year--------", t.year


OUTPUT
=======
------t.year-------- 2011
Traceback (most recent call last):
File "test.py", line 48, in
t.year = 2012
AttributeError: can't set attribute


#====================== OR

class Test(object):
def __init__(self):
self._year = 2011

#property() only works with new-style classes correctly,
#(classe which are inherited from 'object')
@property
def year(self):
return self._year

t = Test()
print "------t.year--------", t.year
t.year = 2012
print "------t.year--------", t.year


OUTPUT
=======
------t.year-------- 2011
Traceback (most recent call last):
File "test.py", line 65, in
t.year = 2012
AttributeError: can't set attribute


----------------------------Note:

# don't use two underscores on the beginning of your attributes
# why ?? any problem ??
# yes, it invokes name mangling
# __ invokes magic
# which is not what you want
# use a single underscore to denote "private"

http://fosshelp.blogspot.com/2010/04/public-and-private-variables-in-python.html

No comments:

Post a Comment