python基础-类的继承
生活随笔
收集整理的這篇文章主要介紹了
python基础-类的继承
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
繼承可以把父類的所有功能都直接拿過來,這樣就不必重零做起,子類只需要新增自己特有的方法,也可以把父類不適合的方法覆蓋重寫
格式:class 子類(父類):
子類可以繼承或重寫父類的方法
子類可以自定義新的方法或成員變量
class Parent: #定義父類parentAttr = 100def __init__(self):print("調用父類構造函數")def parentMethond(self):print("調用父類方法parentMethod")def setAttr(self,attr):Parent.parentAttr = attrdef getAttr(self):print("父類屬性:",Parent.parentAttr)class Child(Parent): #定義子類def __init__(self):print("調用子類構造函數方法")def childMethod(self):print("調用子類方法childMethod")c = Child() #實例化子類 c.childMethod() #調用子類的方法 c.parentMethond() #調用父類方法 c.setAttr(200) #再次調用父類方法 c.getAttr() #再次調用父類方法結果:
調用子類構造函數方法
調用子類方法childMethod
調用父類方法parentMethod
父類屬性: 200
?
方法重寫:
print("\n方法重寫") class Parent: #定義父類def myMethod(self):print("調用父類方法")class Child(Parent):#定義子類def myMethod(self):print("調用子類方法")c = Child() #定義一個子類 c.myMethod() #子類調用重寫方法結果:
方法重寫
調用子類方法
?
練習:
實現一個Shape類(圓),有getArea方法計算面積,有getLong方法計算周長
1、引入math模塊
2、圓的面積:π*r*r 圓的周長:π*2*r
3、math.pi
結果:
半徑為3.5面積38.48
周長為3圓的周長:21.99
半徑為4面積50.27
周長為4圓的周長:25.13
?
轉載于:https://www.cnblogs.com/R-bear/p/7011628.html
總結
以上是生活随笔為你收集整理的python基础-类的继承的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【代码笔记】iOS-TableViewO
- 下一篇: (转)无特征过狗一句话猥琐思路