[Tutor] creating read only attributes
Daniel Ehrenberg
littledanehren at yahoo.com
Fri Nov 21 21:27:06 EST 2003
--- Thomi Richards wrote:
> Hi guys,
>
>
> I've been looking at some Delphi recently, and you
> can create read only
> attributes, which behave like variables. consider
> the following code:
>
> type TTest = class
> private
> testvar = integer;
> public
> property Test: integer read testvar;
> constructor Create;
> end;
>
>
> Now, while I *hate* Delphi code with a vengeance,
> this is pretty cool; I can
> not do something like this:
>
> t := TTest.Create;
> writeln(t.Test);
>
> i.e.- the "Test" property looks and behaves exactly
> like a normal variable,
> except that it is read-only in this case.
>
> The property can even be the result of a function,
> like so:
>
>
> type TTest = class
> private
> function test: integer;
> public
> property Test: integer read test;
> constructor Create;
> end;
>
> And it is still used like 'Test" as a normal
> variable. This has the obvious
> advantage of being able to change the code within a
> class, without having to
> change external code which implements these
> features. (does that make sense)?
>
> I'm sure there's a way to do this in python, but I
> haven't found it yet.
>
> A common usage I've seen is having method names like
> "set_text" and
> "get_text", but these still behave like functions.
> You cannot do something
> like this:
>
> t.set_text = 123.456
>
> well, you could, but it wouldn't do what you
> expected....
>
> Can someone please point me in the right direction?
> what's the magic keyword
> I'm missing?
>
>
> Thanks in advance ;)
>
> - --
> Thomi Richards,
> http://once.sourceforge.net/
There is no native thing to do this, but it can
probably be done using __setattr__, but I can't do it
without getting an infinite recursion. However, I
don't see why you really need to do this. It is a
convention to not change things that are in allcaps,
so if someone wants to write a working application,
they probably won't do that. In general, creating
private variables is considered unpythonic, so it is
probably the same for these immutable variables.
Daniel Ehrenberg
__________________________________
Do you Yahoo!?
Free Pop-Up Blocker - Get it now
http://companion.yahoo.com/
More information about the Tutor
mailing list