Question

I am going through the code of threading module(<Python Home>/lib/threading.py) on Active python 2.7.2 32 bit for Windows. In the __init__ function of the class Thread, there are many variables defined:

self.__target = target
self.__name = str(name or _newname())
self.__args = args
self.__kwargs = kwargs
self.__daemonic = self._set_daemon()
self.__ident = None
self.__started = Event()
self.__stopped = False
self.__block = Condition(Lock())
self.__initialized = True

Here is how I am calling the __init__ function of class Thread:-

class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs={}, Verbose=None):

        Thread.__init__(self, group, target, name, args, kwargs, Verbose)
        self._return = None
        print 'in init: ', self._Thread__target

I fail to understand that the variable self._Thread__target is not initialised anywhere in the __init__ function of class Thread. But, if I print this variable in my own __init__ function, the actual value for self.__target from class Thread's __init__ function is shown.

Also, I tried to edit the threading module and put this line as the last line of the __init__ function of class Thread:-

print 'in init of Thread class in threading: ', self._Thread__target

Still, I could see the value being printed and the interpreter does not display me any errors. So, I tried to find any function which might be doing the renaming stuff. But, could not find it.

This is happening with all the other variables defined in the __init__ function of class Thread. I want to know how the variables like self.__target are getting renamed to self._Thread__target.

Was it helpful?

Solution

this is called name mangling it is what happens every time a variable starts with a __

see : http://docs.python.org/release/1.5/tut/node67.html and http://docs.python.org/reference/expressions.html#atom-identifiers

OTHER TIPS

It is built into Python. From the documentation:

When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name in front of the name, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top