Python進階之一

來源:互聯網
上載者:User

標籤:錯誤   重寫   繼承   新手   blog   括弧   body   類的方法   進階   

  希望前面兩篇Pyhon的基礎知識對於剛接觸Python的新手有點用,接下來我會寫物件導向方面的知識

  首先說一下繼承吧。什麼是繼承呢,簡單點說就是兒子繼承老子的家產,比方說我們建立了一個people類這個類裡面有name,有age等。

然後我們在建立一個student類這個類裡面有stuID,有class等。我們讓student繼承people,那麼我們在調用student的時候也可以調用people

裡面的屬性了。

  代碼如下:

class People:    def __init__(self,name,age):        self.__dict__["name"]=name        self.__dict__["age"]=age    def __setattr__(self, key, value):        self.__dict__[key]=value    def __getattr__(self, item):        return self.__dict__[item]    def show(self):        print("我的名字是",self.name)#Student類繼承Peopleclass Student(People):    a=0 #這個就是靜態屬性    def __init__(self,name,age,id,stuClass):        super().__init__(name,age)        self.__dict__["id"] = id  #執行個體屬性        self.__dict__["stuClass"] = stuClass    def __setattr__(self, key, value):        self.__dict__[key]=value    def __getattr__(self, item):        return self.__dict__[item]    def show(self):        super().show()        print("我的年齡是", self.__dict__["age"])s=Student("hans",21,"12121",2) #類的執行個體化print(s.name)   #輸出hanss.show()  #先執行父類在執行子類  子類重寫父類的方法

1.繼承

  上面的代碼比如Student就繼承了People,所以Student可以調用People裡面的屬性和方法,上面代碼上都有標註,就不在累述了。

2.執行個體化

  在上面代碼中s=Student()這個就是類的執行個體化了,括弧裡面寫的是具體要傳的參數

3.存取修飾詞(沒喲直接的存取修飾詞)

  public   公開的 : 任何方法都可以調用

  private   私人的  : 只有自己可以訪問   __xxx(在屬性的前面加兩個底線)

  proctected  保護 : 只有自己和子類可訪問  _xxx(在屬性前面加一個底線)

4.靜態成員

  例如上面代碼中a就是靜態屬性

  靜態方法s=Student() Student.show(s) 靜態方法用類名直接調用,需要傳入一個執行個體

5.類裡面屬性的get和set

  在上年代碼中在Python裡面直接重寫getattr和setattr

好了這篇就到這裡了,如有錯誤請留言,謝謝:)


 

  

Python進階之一

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.