[Tutor] Const on Python
john at fouhy.net
Thu Mar 6 01:30:23 CET 2008
On 06/03/2008, Tiago Katcipis <katcipis at inf.ufsc.br> wrote:
> learning. Im used to develop on c++ and java and i wanted to know if
> there is any way to create a final or const member, a member that after
> assigned cant be reassigned. Thanks to anyone who tries to help me and
> sorry to bother with a so silly question. i hope someday i can be able
> to help :-)
The short answer is: "Not really".
Actually, with recent versions of python, you could do something with
>>> class MyClass(object):
... def fget_FOO(self):
... return 'foo'
... FOO = property(fget=fget_FOO)
>>> x = MyClass()
>>> x.FOO = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
property() takes up to three arguments: get, set, and docstring. In
this case, I omitted the setter. Thus python doesn't allow me to set
that attribute. You could also mess around with getattr() to achieve
a similar effect.
Generally, though, python takes the attitude that programmers are
adults capable of thinking for themselves, and if you're silly enough
to reassign a constant, you deserve whatever you get. Best just to
make your variable names ALL_CAPS and write documentation saying
they're constant :-)
See also this recipe:
for another take on the issue.
More information about the Tutor