OOP techniques in Python

Edward Elliott nobody at 127.0.0.1
Thu Apr 27 15:22:23 EDT 2006


Panos Laganakos wrote:
> i.e. we usually define private properties and provide public functions
> to access them, in the form of:
> get { ... } set { ... }
> 
> Should we do the same in Python:
> Or there's no point in doing so?
> 
> Some other techniques come to mind, but I think that Python tends to
> allow the programmer to access stuff he wants even though he shouldn't
> or in the form of a dict or list, rather than a method to do so.

There's no point.  Private access can only be advisory anyway -- there are
ways around it in every language.  Convention serves just as well, people
know that touching _foo is done at their own risk.  It's not creating extra
hoops to jump through the few times you really do need to touch a private
var.

Others already mentioned how to transparently change attributes to
properties.

If you're worried about enforcing restrictions in your code base, get a lint
checker to flag any expression of the form name._foo where name isn't
'self'.  Yes you can still access _foo other ways, but you'll never get
perfect enforcement anyway.  Maybe the extra step will make you think
twice, if that's what you want (and it seems to be).




More information about the Python-list mailing list