Double Underscore __ : Introduction « Class « Python Tutorial






Attributes that begin with __ are mangled during runtime so direct access is thwarted. 
Module-level privacy is provided by using a single underscore _ prefixing an attribute name. 
This prevents a module attribute from being imported with "from mymodule import *". 
It will work with functions too.

class WrapMe(object):
    def __init__(self, obj):
        self.__data = obj
    def get(self):
        return self.__data
    def __repr__(self):
        return 'self.__data'
    def __str__(self):
        return str(self.__data)
    def __getattr__(self, attr):
        return getattr(self.__data, attr)

wrappedComplex = WrapMe(3.5+4.2j)

print wrappedComplex                
print wrappedComplex.real           
print wrappedComplex.imag           
print wrappedComplex.conjugate()    
print wrappedComplex.get()          

wrappedList = WrapMe([123, 'foo', 45.67])
wrappedList.append('bar')
wrappedList.append(123)
print wrappedList
print wrappedList.index(45.67)
print wrappedList.count(123)
print wrappedList.pop()
print wrappedList

f = WrapMe(open('/etc/motd'))
print f
print f.get()
print f.readline()
print f.tell()
print f.seek(0)
print f.readline(),
f.close()
print f.get()








11.1.Introduction
11.1.1.Common operator overloading methods
11.1.2.Double Underscore __
11.1.3.Special Class Attributes
11.1.4.__dict__ is a dictionary representing its attributes:
11.1.5.Special Instance Attributes
11.1.6.Built-in Type Attributes
11.1.7.Metaclass Example
11.1.8.Related Modules and Documentation