Python進階之一
阿新 • • 發佈:2018-03-06
訪問 pyhon body gpo xxx 老子 代碼 保護 color
希望前面兩篇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類繼承People class 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) #輸出hans s.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進階之一