溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python魔術(shù)方法怎么用

發(fā)布時(shí)間:2020-09-24 14:19:17 來源:億速云 閱讀:114 作者:Leah 欄目:編程語言

本篇文章為大家展示了python魔術(shù)方法怎么用,內(nèi)容簡明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

準(zhǔn)備工作

為了確保類是新型類,應(yīng)該把 _metaclass_=type 入到你的模塊的最開始。

class NewType(Object):
  mor_code_here
class OldType:
  mor_code_here

在這個(gè)兩個(gè)類中NewType是新類,OldType是屬于舊類,如果前面加上 _metaclass_=type ,那么兩個(gè)類都屬于新類。

 構(gòu)造方法

構(gòu)造方法與其的方法不一樣,當(dāng)一個(gè)對(duì)象被創(chuàng)建會(huì)立即調(diào)用構(gòu)造方法。創(chuàng)建一個(gè)python的構(gòu)造方法很簡答,只要把init方法,從簡單的init方法,轉(zhuǎn)換成魔法版本的_init_方法就可以了。

class FooBar:
    def __init__(self):
        self.somevar= 42
          
>>> f=FooBar()
>>> f.somevar
42

重寫一個(gè)一般方法

每一個(gè)類都可能擁有一個(gè)或多個(gè)超類(父類),它們從超類那里繼承行為方法。

class A:
    def hello(self):
        print 'hello . I am A.'
class B(A):
  pass
>>> a= A()
>>> b= B()
>>> a.hello()
hello . I am A.

因?yàn)锽類沒有hello方法,B類繼承了A類,所以會(huì)調(diào)用A 類的hello方法。

在子類中增加功能功能的最基本的方式就是增加方法。但是也可以重寫一些超類的方法來自定義繼承的行為。如下:

class A:
    def hello(self):
        print 'hello . I am A.'
class B(A):
    def hello(self):
        print 'hello . I am  B'
>>> b= B()
>>> b.hello()
hello . I am  B

特殊的和構(gòu)造方法

重寫是繼承機(jī)制中的一個(gè)重要內(nèi)容,對(duì)一于構(gòu)造方法尤其重要??聪旅娴睦樱?/p>

class Bird:
    def __init__(self):
        self.hungry= True
    def eat(self):
        if self.hungry:
            print 'Aaaah...'
            self.hungry= False
        else:
            print 'No, thanks!'
>>> b= Bird()
>>> b.eat()
Aaaah...
>>> b.eat()
No, thanks!

這個(gè)類中定義了鳥有吃的能力, 當(dāng)它吃過一次后再次就會(huì)不餓了,通過上面的執(zhí)行結(jié)果可以清晰的看到。

那么用SongBird類來繼承Bird 類,并且給它添加歌唱的方法:

class Bird:
    def __init__(self):
        self.hungry= True
    def eat(self):
        if self.hungry:
            print 'Aaaah...'
            self.hungry= False
        else:
            print 'No, thanks!'
              
class SongBird(Bird):
         def __init__(self):
                 self.sound= 'Squawk!'
         def sing(self):
                 print self.sound
>>> s= SongBird()
>>> s.sing()
Squawk!
>>> s.eat()
Traceback (most recent call last):
  File "<pyshell#26>", line1,in <module>
    s.eat()
  File "C:/Python27/bird", line6,in eat
    if self.hungry:
AttributeError:'SongBird' object has no attribute'hungry'

異常很清楚地說明了錯(cuò)誤:SongBird沒有hungry特性。原因是這樣的:在SongBird中,構(gòu)造方法被重寫,但新的構(gòu)造方法沒有任何關(guān)于初始化hungry特性的代碼。為了達(dá)到預(yù)期的效果,SongBird的構(gòu)造方法必須調(diào)用其超類Bird的構(gòu)造方法來確保進(jìn)行基本的初始化。

兩種方法實(shí)現(xiàn):

一 、調(diào)用未綁定的超類構(gòu)造方法

class Bird:
    def __init__(self):
        self.hungry= True
    def eat(self):
        if self.hungry:
            print 'Aaaah...'
            self.hungry= False
        else:
            print 'No, thanks!'
              
class SongBird(Bird):
         def __init__(self):
                 Bird.__init__(self)
                 self.sound= 'Squawk!'
         def sing(self):
                 print self.sound
>>> s= SongBird()
>>> s.sing()
Squawk!
>>> s.eat()
Aaaah...
>>> s.eat()
No, thanks!

在SongBird類中添加了一行代碼Bird.__init__(self) 。 在調(diào)用一個(gè)實(shí)例的方法時(shí),該方法的self參數(shù)會(huì)被自動(dòng)綁定到實(shí)例上(這稱為綁定方法)。但如果直接調(diào)用類的方法,那么就沒有實(shí)例會(huì)被綁定。這樣就可以自由地提供需要的self參數(shù)(這樣的方法稱為未綁定方法)。

通過將當(dāng)前的實(shí)例作為self參數(shù)提供給未綁定方法,SongBird就能夠使用其超類構(gòu)造方法的所有實(shí)現(xiàn),也就是說屬性hungry能被設(shè)置。

二、使用super函數(shù)

__metaclass__= type  #表明為新式類
class Bird:
    def __init__(self):
        self.hungry= True
    def eat(self):
        if self.hungry:
            print 'Aaaah...'
            self.hungry= False
        else:
            print 'No, thanks!'
              
class SongBird(Bird):
         def __init__(self):
                 super(SongBird,self).__init__()
                 self.sound= 'Squawk!'
         def sing(self):
                 print self.sound
>>> s.sing()
Squawk!
>>> s.eat()
Aaaah...
>>> s.eat()
No, thanks!

super函數(shù)只能在新式類中使用。當(dāng)前類和對(duì)象可以作為super函數(shù)的參數(shù)使用,調(diào)用函數(shù)返回的對(duì)象的任何方法都是調(diào)用超類的方法,而不是當(dāng)前類的方法。那就可以不同在SongBird的構(gòu)造方法中使用Bird,而直接使用super(SongBird,self)。

 屬性

訪問器是一個(gè)簡單的方法,它能夠使用getHeight 、setHeight 之樣的名字來得到或者重綁定一些特性。如果在訪問給定的特性時(shí)必須要采取一些行動(dòng),那么像這樣的封裝狀態(tài)變量就很重要。如下:

class Rectangle:
    def __init__(self):
        self.width= 0
        self.height= 0
    def setSize(self,size):
        self.width ,self.height= size
    def getSize(self):
        return self.width ,self.height
>>> r= Rectangle()
>>> r.width= 10
>>> r.height= 5
>>> r.getSize()
(10,5)
>>> r.setSize((150,100))
>>> r.width
150

在上面的例子中,getSize和setSize方法一個(gè)名為size的假想特性的訪問器方法,size是由width 和height構(gòu)成的元組。

 property 函數(shù)

property函數(shù)的使用很簡單,如果已經(jīng)編寫了一個(gè)像上節(jié)的Rectangle 那樣的類,那么只要增加一行代碼:

__metaclass__= type
class Rectangle:
    def __int__(self):
        self.width= 0
        self.height= 0
    def setSize(self,size):
        self.width,self.height= size
    def getSize(self):
        return self.width ,self.height
    size= property(getSize ,setSize)
>>> r= Rectangle()
>>> r.width= 10
>>> r.height= 5
>>> r.size
(10,5)
>>> r.size= 150,100
>>> r.width
150

在這個(gè)新版的Retangle 中,property 函數(shù)創(chuàng)建了一個(gè)屬性,其中訪問器函數(shù)被用作參數(shù)(先取值,然后是賦值),這個(gè)屬性命為size 。這樣一來就不再需要擔(dān)心是怎么實(shí)現(xiàn)的了,可以用同樣的方式處理width、height 和size。

上述內(nèi)容就是python魔術(shù)方法怎么用,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI