Friday, November 02, 2007

Creating Constants in Python

Some people say that creating constants in Python is something that can not and should not be done. However, if you have the need to create a class constant in Python, here is some code to get you started. The code appears below:


class Test( object ):
def getA( self ):

return 5


a = property( getA )


###############


t = Test()

print 'a=', t.a

t.a = 20


#print 'deleting...'

#del t.a



Try to set the class constant 'a', and you receive an AttributeError. Try to delete the class constant, and you also receive an AttributeError (uncomment the lines, first).