類的私有屬性

2022-08-24 08:30:16 字數 696 閱讀 5051

前面帶有兩下劃線代表是私有屬性,能在類的內部呼叫,不能在類的外部呼叫,示例:

class

money:

__self = 50

all = 300

def gives(self):

print('給錢

',self.__self)

def givea(self):

print('給錢

',self.all)

a =money()

a.gives()

a.givea()

輸出:

給錢 50

給錢 300

執行

print(a.__self)

輸出報錯:

attributeerror                            traceback (most recent call last)

54-d67a9ccaa360> in

----> 1

print(a.__self)

attributeerror:

'money

'object has no attribute '

__self

'

執行

print(a.all)

輸出:

300

類的建構函式 私有屬性,私有屬性不 絕對 私有

建構函式及其他 class a def init self self.hour 0 self.minute 0 init 為類的建構函式,每次建立類物件時,都會執行建構函式。建構函式 init 會初始化類物件屬性,並且返回none。python類還可以定義其他的特殊方法,這些方法之前 之後都會有雙下...

python類私有屬性

python中沒有private關鍵字,想要建立乙個類私有的變數需要通過命名規則來實現 在變數名之前加兩個下劃線 name,則在類外部就不能直接通過例項.name訪問,具體原理python編譯器將其命名修改為了 類名 name,通過其實例項.類名 name還是可以訪問 class test obje...

類的私有屬性和私有方法

class role def init self,name,role,weapon,value 100,money 1500 建構函式 self.name name 例項變數 靜態屬性 作用域就是實力本身 self.role role self.weapon weapon self.value va...