python基础-类的继承

继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写

格式:class 子类(父类):

子类可以继承或重写父类的方法

子类可以自定义新的方法或成员变量

class Parent:  #定义父类
    parentAttr = 100
    def __init__(self):
        print("调用父类构造函数")
    
    def parentMethond(self):
        print("调用父类方法parentMethod")
    
    def setAttr(self,attr):
        Parent.parentAttr = attr
        
    def 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("
方法重写")
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

import math

class Shape:
    def __init__(self,r):
        self.r = r
    def get_area(self):
        print("半径为%s面积%.2f"%(self.r,math.pi*(self.r**2)))
    def get_length(self):
        print("周长为%d圆的周长:%.2f"%(self.r,math.pi*self.r*2))

c=Shape(3.5)
c.get_area()
c.get_length()


shape2 = Shape(4)
shape2.get_area()
shape2.get_length()

结果:

半径为3.5面积38.48
周长为3圆的周长:21.99
半径为4面积50.27
周长为4圆的周长:25.13

原文地址:https://www.cnblogs.com/R-bear/p/7011628.html