[Tutor] Const on Python
Alan Gauld
alan.gauld at btinternet.com
Fri Mar 7 00:42:39 CET 2008
> Now coming back to your question, that you want a non-changeable
> name,
> well, one can create such a beast, e.g.:
>
> def constant(value):
> ...
>class Test(object):
> const_a = constant(123)
> This creates a member that can only be fetched, but not set or
> deleted.
Only within constant. the member const_a can be changed
via simple assignment.
> But in practice, I personally never have seen a need for something
> like
> this. You can always overcome the above constant. Btw, you can do
> that
> in C++ privates too, worst case by casting around and ending up with
> a
> pointer that points to the private element ;)
I've seen an even more mundane trick to bypass private(rather than
const):
#define private public
#define protected public
#include "someclass.h"
SomeClass c = new SomeClass;
c->someVar = 42;
etc...
I suppose you could avoid that by prefixing every classs definition
with
#define private private
#define protected protected
class SomeClass{....};
But it illustrates the relative fragility of C++ apparently tight
control
of names and visibility. And with a pointr to the right memory
location and a cast you can do just about anything...
In that respect I prefer the blatant openness of Python to the
perceived protection of C++
Alan G.
More information about the Tutor
mailing list