国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 方法中變量加self和不加的區別

2019-11-09 19:28:08
字體:
來源:轉載
供稿:網友

這段代碼我覺得很好的說明了python中類的方法在加self和不加self的區別。

123456789101112131415161718192021222324252627282930313233343536373839404142434445>>> class AAA(object):...     def go(self):...         self.one = 'hello'...>>> class BBB(object):...     def go(self):...         one = 'hello'...>>> a1 = AAA()>>> a1.go()>>> a1.one'hello'>>> a2 = AAA()>>> a2.oneTraceback (most recent call last):  File "<stdin>", line 1in <module>AttributeError: 'AAA' object has no attribute 'one'>>> a2.go()>>> a2.one'hello'>>> b1 = BBB()>>> b1.go()>>> b1.oneTraceback (most recent call last):  File "<stdin>", line 1in <module>AttributeError: 'BBB' object has no attribute 'one'>>> BBB.oneTraceback (most recent call last):  File "<stdin>", line 1in <module>AttributeError: type object 'BBB' has no attribute 'one'>>> class BBB(object):...     def go(self):...         one = 'hello'...         PRint one...         self.another = one...>>> b2 = BBB()>>> b2.go()hello>>> b2.another'hello'>>> b2.oneTraceback (most recent call last):  File "<stdin>", line 1in <module>AttributeError: 'BBB' object has no attribute 'one'

個人認為方法中加self的變量可以看成是類的屬性,或者是特性。使用方法改變和調用屬性,屬性改變實例的狀態。方法中不加self的變量可以看成一個局部變量,該變量不能被直接引用。

類本身的局部變量(個人的認為定義在方法以外不以self開頭的變量是類本身的局部變量)是可以被直接掉用的,注意這里不是指上面所說的方法內的局部變量(這兩個命名空間不同)。如果方法中有有變量與類的局部變量同名,那么方法中的局部變量將會屏蔽類中的局部變量即類中的局部變量不在起作用。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 土默特右旗| 鹤壁市| 梁平县| 西丰县| 大理市| 万源市| 洪湖市| 江都市| 祁东县| 临西县| 屏南县| 黔东| 兴隆县| 榆树市| 通化市| 平果县| 满洲里市| 确山县| 海林市| 温州市| 磐安县| 顺义区| 苍梧县| 上饶市| 鸡东县| 万盛区| 禹城市| 平潭县| 蒙山县| 嫩江县| 北票市| 抚州市| 晋城| 东山县| 浦北县| 东平县| 泸溪县| 宜黄县| 盐城市| 西吉县| 普宁市|