Class Inheritance - What am I doing wrong?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Apr 25 10:56:43 EDT 2008


Brian Munroe a écrit :
> Ok, so thanks everyone for the helpful hints.  That *was* a typo on my
> part (should've been super(B...) not super(A..), but I digress)
> 
> I'm building a public API.  Along with the API I have a few custom
> types that I'm expecting API users to extend, if they need too.  If I
> don't use name mangling, isn't that considered bad practice (read not
> defensive programming) to not protect those 'private' fields?

There would be a lot to say about whether defensive programming is a 
good practice or not. At least in the context of hi-level languages with 
exception handling and automatic memory management.

Anyway:
- there's just no way to make anything truly "private" in Python
- the convention is that attributes (including methods - they are 
attributes too) whose name starts with a single leading underscore are 
implementation stuff and should not be messed with. IOW, the contract is 
"mess with them and you're on your own".
- name mangling is only useful when you really need to make sure an 
implementation attribute won't be *accidentally* shadowed. These 
attributes should only be used by methods that are not themselves 
supposed to be overridden or extended by user code. FWIW, I must have 
used them less than half a dozen times in 7+ years (and I wrote more 
than a couple mini-frameworks, with lot of black-juju metaclasses and 
custom descriptors magic in them).

So just use single-leading-underscore for implementation attributes, and 
document what the users are supposed to extend and what they're supposed 
to leave alone.

My 2 cents.



More information about the Python-list mailing list