不需要为 python 中相同 class 的另一个对象进行名称修改?

no need of name mangling for another object of the same class in python?

我是Python新手,正在学习名称修改(双下划线),我已经搜索并学习了,但是我有一个问题,无法通过搜索得到答案:我们不知道在 class 函数中处理同一 class 的另一个对象时不需要名称重整,对吗?看我的测试代码:

import math
class Point:
    def __init__(self, loc_x, loc_y):
        self.__x = loc_x
        self.__y = loc_y
    def distance(self, other):
        return math.sqrt((self.__x - other.__x) * (self.__x - other.__x) + (self.__y - other.__y) * (self.__y - other.__y))
class Point1:
    def __init__(self, loc_x, loc_y):
        self.__x = loc_x
        self.__y = loc_y
#two points of same class
p1 = Point(1,2)
p2 = Point(2,3)
print (p1.distance(p2))
#object of another point class
p3 = Point1(4,5)
print (p1.distance(p3))

如果使用双下划线来使用名称修饰,则只能在 class 上的方法中引用该变量。任何时候写

obj.__var

在 class 方法中,Python 会将其替换为

obj.__ClassName_var

其中 ClassName 是该方法的 class 的名称。

名称修饰在 编译时 起作用,并用修饰后的版本替换以两个下划线开头的 任何 属性的名称。

考虑以下因素:

>>> class Foo:
...     def __init__(self):
...         bar.__x += 1
... 
>>> import dis
>>> dis.dis(Foo.__init__)
  3           0 LOAD_GLOBAL              0 (bar)
              3 DUP_TOP             
              4 LOAD_ATTR                1 (_Foo__x)
              7 LOAD_CONST               1 (1)
             10 INPLACE_ADD         
             11 ROT_TWO             
             12 STORE_ATTR               1 (_Foo__x)
             15 LOAD_CONST               0 (None)
             18 RETURN_VALUE        
>>> 

如您所见,bar.__x 的代码已被编译为 bar._Foo__x。无论调用该代码时 bar 的类型是什么,都会发生这种情况。在这种情况下,即使在访问全局成员时也会发生名称重整。

请注意,如果您发现自己经常使用名称修改,那么您可能做错了什么。 Python 程序员可以在不需要私有数据成员的情况下快乐地生活一段时间。

这也是因为在 Python 中不需要像其他语言那样频繁的推导,这要归功于委托和鸭子类型...