Search code examples
pythondictionaryinstance-variablespython-internals

built in __dict__ is returning names of attributes with class names as prefix


class Enrollment(object):

    def __init__(self,enrollmentId=None, enrollmentReference=None):
        self.enrollmentId = enrollmentId
        self.enrollmentReference = enrollmentReference

    @property
    def enrollmentId(self):
        return self.__enrollmentId

    @enrollmentId.setter
    def enrollmentId(self, enrollmentId):
        self.__enrollmentId = enrollmentId

    @property
    def enrollmentReference(self):
        return self.__enrollmentReference

    @enrollmentReference.setter
    def enrollmentReference(self, enrollmentReference):
        self.__enrollmentReference = enrollmentReference

If i now try to print the attributes of the above class:

print(Enrollment().__dict__)

It prints the attributes prefixed with class name as below:

{'_Enrollment__enrollmentId': None, '_Enrollment__enrollmentReference': None}

Note: If I remove object as the super class, all works well and it prints the attributes correctly as below:

{'enrollmentId': None, 'enrollmentReference': None}

I have been been wrapping my head around this for 2 days now with no luck. Not able to understand why the class name is prefixed to attributes. I need to serialize the Enrollment object to JSON.


Solution

  • In a class definition, Python transforms __x into _classname__x. This is called name mangling. Its purpose is to support class local references so that subclasses don't unintentionally break the internal logic of the parent class.