I have a large program with multiple classes.
class Dog(object):
def __init__(self):
self.food = 10
def print_dog_food(self):
print(self.food)
class Cat(object):
def __init__(self):
self.food = 5
def print_cat_food(self):
print(self.food)
They are inherited by other classes:
class AllAnimals(Cat, Dog):
def __init__(self):
Cat.__init__(self)
Dog.__init__(self)
Some variables will be having similar names. I am afraid of accidentally overriding an existing variable and creating nasty bugs:
# Wrong result.
AllAnimals().print_cat_food() # prints 10
AllAnimals().print_dog_food() # prints 10
Keeping track of all those variables to avoid accidents seems impractical, so I was thinking of using mangling:
def __init__(self):
self.__food = ......
and get what i expect:
# Correct result.
AllAnimals().print_cat_food() # prints 5
AllAnimals().print_dog_food() # prints 10
Mangling solves my problem, but reading this highly upvoted answer stating that:
If you want to use it eventually, you can, but it is neither usual nor recommended.
and the "This is culture" section of that answer makes me sceptical.
Questions:
- Should I use mangling as in the example?
- If not, what are my alternatives to avoid accidental overriding of variables?