python - 如何避免不小心弄乱Python中的基类?

标签 python oop encapsulation

Python 对私有(private)变量使用下划线约定。但是,似乎没有什么可以阻止您意外地弄乱基类,例如

class Derived(Base):
    def __init__(self, ...):
        ...
        super(Derived, self).__init__(...)
        ...
        self._x = ...

如果 Base 也恰好使用名称 _x

避免此类错误的最佳做法是什么?

如果不同的人实现了BaseDerived类,或者_x被添加到Base中,这似乎特别具有挑战性> Derived 实现后(因此,Derived 的实现将追溯性地破坏封装)

最佳答案

使用private variables with two underscores 。这样,名称修改可以防止您弄乱您的父类(在正常用例中)。

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

[...] Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.

示例

class A(object):
    def __init__(self):
        self.__v = 1
    def __str__(self):
        return "A = {}".format(self.__v)

class B(A):
    def __init__(self):
        A.__init__(self)
        self.__v = 2
    def __str__(self):
        return "{}; B = {}".format(A.__str__(self), self.__v)

a = A()
b = B()
print(a)
print(b)

产量

A = 1
A = 1; B = 2

关于python - 如何避免不小心弄乱Python中的基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38412261/

相关文章:

python - 有没有办法在 Windows 中停止 time.sleep?

Python:类型错误:不可散列的类型: 'slice'

java - Java中的重构: Duplicated attributes

javascript - js : method can't access property

python - 如何在 Python 中将一个类的对象的创建限制为另一个类的实例?

python - 使用 Kaleido 导出 Plotly 图表不起作用?

python - 一些函数参数可以通过装饰器传递吗?

javascript - 使用 Object.Create 将函数添加到 JavaScript 对象

ruby - 为什么要私有(private)封装私有(private)常量?

c++ - 从另一个对象访问一个对象的方法(建议更好的方法?)