Inheritance and name clashes

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Mon Oct 4 07:08:20 CEST 2010


On Sun, 03 Oct 2010 21:32:25 -0700, Dennis Lee Bieber wrote:

> 	Well... then use the double __ prefix so your instance variables
> have a class specific name... That IS what the __ are designed to do --
> ensure that the name, as used /in/ that class itself is unique, and not
> referencing something from some unknown parent class.


Unfortunately name mangling doesn't *quite* do that. It is still possible 
to have name clashes.

Imagine you inherit from a class Ham:


from luncheon_meats import Ham

class Spam(Ham):
    def __init__(self):
        self.__x = "yummy"


You think you're safe, because the attribute __x is mangled to _Spam__x. 
But little do you know, Ham itself inherits from another class Meat, 
which inherits from Food, which inherits from FoodLikeProducts, which 
inherits from... Spam. Which also has an __x attribute.

You now have a name clash.



-- 
Steven



More information about the Python-list mailing list