3 回答

TA貢獻1810條經驗 獲得超5個贊
名稱置亂用于確保子類不會意外地覆蓋其超類的私有方法和屬性。它的設計并不是為了防止故意從外部進入。
例如:
>>> 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}
當然,如果兩個不同的類有相同的名稱,它就會分解。

TA貢獻1818條經驗 獲得超7個贊
私有函數示例
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貢獻1829條經驗 獲得超6個贊
添加回答
舉報