3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
名稱置亂用于確保子類不會(huì)意外地覆蓋其超類的私有方法和屬性。它的設(shè)計(jì)并不是為了防止故意從外部進(jìn)入。
例如:
>>> class Foo(object):
... def __init__(self):
... self.__baz = 42
... def foo(self):
... print self.__baz
...
>>> class Bar(Foo):
... def __init__(self):
... super(Bar, self).__init__()
... self.__baz = 21
... def bar(self):
... print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}
當(dāng)然,如果兩個(gè)不同的類有相同的名稱,它就會(huì)分解。

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊
私有函數(shù)示例
import reimport inspectclass MyClass : def __init__(self) : pass def private_function ( self ) : try : function_call = inspect.stack()[1][4][0].strip() # See if the function_call has "self." in the begining matched = re.match( '^self\.', function_call ) if not matched : print 'This is Private Function, Go Away' return except : print 'This is Private Function, Go Away' return # This is the real Function, only accessible inside class # print 'Hey, Welcome in to function' def public_function ( self ) : # i can call private function from inside the class self.private_function()### End ###

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
添加回答
舉報(bào)