What python idioms for private, protected and public?
Michael Ekstrand
mekstran at scl.ameslab.gov
Thu Sep 29 10:44:44 EDT 2005
On Thursday 29 September 2005 09:08, Michael Schneider wrote:
> Design Intent:
>
> 1) mark an object as dirty in a setter (anytime the object is
> changed, the dirty flag is set without requiring a user to set the
> dirty flag
2 ways: wrap every attribute that is to be set in a property object (in
new-style classes), and set it in the setter there.
Or override __setattr__ to set the dirty flag.
Or, if you want overkill, but a potentially cleaner interface in some
cases, a metaclass could also be contrived to accomplish this (crud,
you can do _anything_ with a metaclass).
> 2) enforce value constraints (even if just during debugging)
Python's property objects
def _get_foo(self, foo):
return self.__foo
def _set_foo(self, foo, val):
if self.__is_valid_foo(val):
self.__foo = foo
else:
raise ValueError("Invalid foo")
foo = property(_get_foo, _set_foo, doc="Foo property")
> 3) lazy init, don't bring the data in until needed
Define __getattr__. Or use a metaclass (but I tend to think of
metaclasses as a solution to too many things - see previous thread
about synchronization for details).
> 4) adding debug info
A metaclass to do tracing, whatever - they let you modify the nature of
your class greatly on the fly.
> 5) .... more here????
Overriding magic methods (esp. getattr/setattr), various decorators
(ether existing or custom for your purposes), metaclasses, etc.
> I usually violate private when adding an aspect to a class, and
> I don't want this code in every class. Example, persistence.
Persistence can be done with subclassing, with a base class that sets up
persistence (I did this in PHP4 once, an ugly object model if I've ever
seen one). Metaclasses might be cleaner.
> I really like the C# properties, you can access data with a data
> accessor, but add functionality is triggered when accessing the data.
Python has these - use property objects. property() is documented under
Built-In Functions
> I like the data access syntax, better then the set/get functions. I
> need the functionality to achieve the design goals above, so i use
> function, but the are ugly, especially in math code.
Yes, get/set is highly ugly IMHO. I have to do Java for one of my
classes now... I frequently want to gag over the forced usage of such
things.
> It would be easy for me to say "Add public and private to python so I
> can code the way that I am used to". What are some python
> alternatives to achieve the design intents specified above above?
See above :-). I think you'll find that you can accomplish most or all
of your purposes, and then a few you may not have thought of yet.
- Michael
More information about the Python-list
mailing list