避免覆盖超类变量。加工或替代品

Avoiding overriding of superclass variables. Mangling or alternatives

我有一个 大型程序 有多个 类。

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)

它们被其他人继承类:

class AllAnimals(Cat, Dog):
    def __init__(self):
        Cat.__init__(self)
        Dog.__init__(self)

一些变量将具有相似的名称。我害怕不小心覆盖现有变量并产生讨厌的错误:

# Wrong result. 
AllAnimals().print_cat_food()  # prints 10
AllAnimals().print_dog_food()  # prints 10

跟踪所有这些变量以避免事故似乎不切实际,所以我在考虑使用 mangling:

def __init__(self):
    self.__food = ...... 

得到我期望的结果:

# Correct result.
AllAnimals().print_cat_food()  # prints 5
AllAnimals().print_dog_food()  # prints 10

Mangling solves my problem, but reading this highly upvoted answer 表示:

If you want to use it eventually, you can, but it is neither usual nor recommended.

和该答案的 "This is culture" 部分让我怀疑。

问题:
- 我应该像示例中那样使用 mangling 吗?
- 如果没有,我有什么替代方法可以避免意外覆盖变量?

不常用也不推荐使用 mangling 来生成 'private' 属性,因为 Python.

中没有真正的私有属性。

按照其设计 的目的使用重整,减少子类 属性名称冲突的可能性,绝对是 pythonic 并且很好。

来自documentation

Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes.

强调我的。

但是,用例非常少;您希望属性不被意外覆盖的情况并不多。但是,如果您 正在 构建将被广泛子类化的基础 类(在大型项目中或作为用于广泛用途的框架或库的一部分),然后使用双下划线名称作为实现细节就完全没问题了。

这很不寻常,因为你在这里做的事情很不寻常。但是,根据您的要求,我会说使用名称损坏的变量是一件非常合适的事情。