Python類的私有成員

2021-06-08 00:49:27 字數 1027 閱讀 9516

#!/usr/bin/env python

#-*- coding:utf8 -*-

"""python中類的成員函式、成員變數預設都是公開的(public),

在python中定義私有成員只需要在變數名或函式名前加上"__"(兩個下劃線),那麼這個函式或變數就變成私有的了。

在內部,python使用一種name mangling技術,將__membername替換成_classname__membername,

所以你在外部使用原來的私有成員的名字時,會提示找不到。

python的私有成員並不是真正意義上的私有,在類外部也可以呼叫。

"""class test(object):

def __init__(self):

super(test, self).__init__();

self.__message = 'hello world!'

def __getmessage(self):

print self.__message

if __name__ == '__main__':

obj = test()

print dir(obj)

print obj._test__message

obj._test__getmessage()

"""['_test__getmessage', '_test__message', '__class__', '__delattr__', '__dict__',

'__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__

', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeo

f__', '__str__', '__subclasshook__', '__weakref__']

hello world!

hello world!

"""

python 類私有成員

在python中定義私有變數只需要在變數名或函式名前加上 兩個下劃線,那麼這個函式或變數就會為私有的了。created on 2012 7 24 author administrator class test def test 1 self print test 1 is ok.def test 2...

Python類中的私有成員 私有函式,私有變數

在python中定義私有變數只需要在變數名或函式名前加上 兩個下劃線,那麼這個函式或變數就會為私有的了。在內部,python使用一種 name mangling 技術,將 membername替換成 classname membername,所以你在外部使用原來的私有成員的名字時,會提示找不到。命名...

Python類中的私有成員 私有函式,私有變數

python類中的私有成員 私有函式,私有變數 python俱樂部 在python中定義私有變數只需要在變數名或函式名前加上 兩個下劃線,那麼這個函式或變數就會為私有的了。在內部,python使用一種 name mangling 技術,將 membername替換成 classname member...