本文部分内容参考《编程小白的第1本python入门书》,(侯爵著)一书,以及https://www.cnblogs.com/jiangzuofenghua/p/11413777.html该博客。
python允许在一个或多个类的基础上生成新的类,新的类可以使用父类的一些属性和方法。这个过程就叫做继承。
python继承最大的作用就是为了减少代码。
博美、萨摩耶、哈士奇、罗威纳犬等都属于狗类,都可以定义狗类的共同属性,这就是所谓的类的继承。
定义一个dog父类
class dog: #定义一个父类
dog_describe = ["are the most faithful friend of people","were domesticated from wolves by early humans "]
def __init__(self,characteristic):
self.characteristic_describe = characteristic #可以认为是创建实例属性,并为其赋值
def Dog(self):
for i in dog_describe:
print("dogs {}".format(i))
我们在新的类Pomeranian(博美狗)后面的括号放入dog,这就表示该子类继承于dog这个父类。父类中的变量和方法可以完全被子类继承,如需进行改动,也可以进行覆盖。
class Pomeranian(dog): #定义一个Pomeranian(博美犬)子类
def Pomeranian_describe(self): #在子类中定义新方法
self.Dog() #继承父类中的方法
example1 = Pomeranian("flexible and active") #创建实例,并为dog父类中_init_()方法的characteristic的行参赋值
example1.Pomeranian_describe()
#程序运行结果:
Pomeranian_dogs are the most faithful friend of people
Pomeranian_dogs were domesticated from wolves by early humans
我们再举一个例子:
class samoyed(dog): #定义一个samoyed(萨摩耶)子类
def samoyed_characteristic(self): ##在子类中定义新方法
print("samyoed_dogs include these characteristic:%s"%self.characteristic_describe) #继承父类中的实例
example2 = samoyed("a good sense of smell and loyalty") ##创建实例,并为dog父类中_init_()方法的characteristic的行参赋值
example2.samoyed_characteristic()
#程序运行结果:
samyoed_dogs include these characteristic:a good sense of smell and loyalty
附:
博美(Pomeranian)
萨摩耶(samoyed)
如有错误,敬请批评指正!谢谢!