Reputation: 23
I'm new to Python learning about name mangling(double underscore), I've done my search and learned, but I have one question and couldn't get the answer through searching: we don't need name mangling when dealing with another object of the same class in a class function, right? see my test code:
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))
Upvotes: 2
Views: 116
Reputation: 114579
Name mangling works at compile time and replaces the name of any attribute starting with two underscores with the mangled version.
Consider the following:
>>> 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
>>>
As you can notice the code for bar.__x
has been compiled as if it was bar._Foo__x
. This happens no matter what the type of bar
will be when calling that code. In this case name mangling happens even when accessing members of a global.
Note that if you find yourself using name mangling a lot then probably you're doing something wrong. A Python programmer can live happily for quite a while without ever needing private data members.
This happens also because in Python derivation is not needed as often as in other languages thanks to delegation and duck typing...
Upvotes: 2
Reputation: 37559
If you use double underscores to use name mangling, you can only reference that variable in methods on that class. Anytime you write
obj.__var
inside a class method, Python will replace it with
obj.__ClassName_var
Where ClassName
is the name of the class for that method.
Upvotes: 1