Double Underscore __ : Introduction « Class « Python Tutorial

Home
Python Tutorial
1.Introduction
2.Data Type
3.Statement
4.Operator
5.String
6.Tuple
7.List
8.Dictionary
9.Collections
10.Function
11.Class
12.File
13.Buildin Function
14.Buildin Module
15.Database
16.Regular Expressions
17.Thread
18.Tkinker
19.wxPython
20.XML
21.Network
22.CGI Web
23.Windows
Python Tutorial » Class » Introduction 
11.1.2.Double Underscore __
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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.