日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python的魔法方法--__

發布時間:2025/3/15 python 9 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python的魔法方法--__ 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
__init__方法又成為構造方法,創造的方法會被自動的調用 以下為相應的__init__方法方法的展示與調用 以下是使用了__init__的方法 In [50]: class ball:...: def __init__(self,name):...: self.name=name...: def kick(self):...: print "我叫 %s,該死的是誰踢了我。。。。" % self.name...: In [52]: b=ball('土豆')In [53]: b.kick() 我叫 土豆,該死的是誰踢了我。。。。

以下是未使用init的方法

In [37]: class ball:...: def setName(self,name):...: self.name=name...: def kick(self):...: print "my name is %s,shit who shot me...." % self.name...: In [38]: a=ball()In [39]: a.setName('球A')In [40]: b=ball()In [41]: b.setName('westing')In [43]: c=ball()In [44]: c.setName('球B')In [45]: a.kick() my name is 球A,shit who shot me....In [46]: b.kick() my name is westing,shit who shot me....In [47]: c.kick() my name is 球B,shit who shot me....

對比之后就會發現使用了init的方法的類更加的簡潔

函數的私有化
若想將一個變量進行私有化,只需在相應的變量名字前加上 ’_‘即可:

In [54]: class person:...: name='andrew'...: In [55]: a=person()In [56]: a.name Out[56]: 'andrew'In [57]: class person:...: __name='andrew'...: In [58]: a=person()In [59]: a.__name --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-59-5d5520ef9fe0> in <module>() ----> 1 a.__nameAttributeError: person instance has no attribute '__name'In [60]: a.name --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-60-c0a6f6c60584> in <module>() ----> 1 a.nameAttributeError: person instance has no attribute 'name'

一旦變量名字的前方加上’_’ 函數就會對相應的變量進行私有化,這時要想進行相應的引用只有在函數內部引用,在外部變量名字會被隱藏起來。
調用的方法如下:

In [61]: class person:...: __name='andrew'...: def getName(self):...: return self.__name...: In [63]: p=person()In [64]: p.name --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-64-1c57ed665d7c> in <module>() ----> 1 p.nameAttributeError: person instance has no attribute 'name'In [65]: p.__name --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-65-5fe22c1da0df> in <module>() ----> 1 p.__nameAttributeError: person instance has no attribute '__name'In [66]: p.getName() Out[66]: 'andrew'

其實加上’_‘也就相當于進行類名的重整,也就是你加上的只是’__‘但是python 會默認給你加上的為_類名__變量名 的形式,
以下就是直接訪問重整變量__變量 類型變量
“`

In [67]: class person:
…: __name=’andrew’
…:

In [68]:

In [68]: p._person__name
Out[68]: ‘andrew’

總結

以上是生活随笔為你收集整理的python的魔法方法--__的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。