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

首頁 > 編程 > Python > 正文

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

2019-11-09 20:03:34
字體:
來源:轉載
供稿:網友

這段代碼我覺得很好的說明了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開頭的變量是類本身的局部變量)是可以被直接掉用的,注意這里不是指上面所說的方法內的局部變量(這兩個命名空間不同)。如果方法中有有變量與類的局部變量同名,那么方法中的局部變量將會屏蔽類中的局部變量即類中的局部變量不在起作用。


上一篇:python topn

下一篇:Python線程進程

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 凭祥市| 宜宾县| 九寨沟县| 民和| 东光县| 合肥市| 清河县| 五华县| 正宁县| 霸州市| 梓潼县| 塘沽区| 延安市| 长寿区| 崇左市| 正镶白旗| 汾阳市| 敦煌市| 离岛区| 孝感市| 南昌市| 新蔡县| 渭源县| 兴化市| 汝南县| 漳浦县| 凯里市| 固原市| 尚志市| 个旧市| 余庆县| 广元市| 睢宁县| 如皋市| 宁陕县| 常山县| 清丰县| 布尔津县| 霍山县| 温宿县| 定襄县|