如何避免意外地弄乱Python中的基类?

2024-05-16 01:49:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

ifBase也恰好使用了名称_x。你知道吗

避免这种错误的最佳做法是什么?你知道吗

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


Tags: self名称baseinitdef错误基类class
1条回答
网友
1楼 · 发布于 2024-05-16 01:49:12

使用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

相关问题 更多 >