网络编程
位置:首页>> 网络编程>> Python编程>> 对python中类的继承与方法重写介绍

对python中类的继承与方法重写介绍

作者:墨墨陌陌沫沫0  发布时间:2023-03-21 09:49:20 

标签:python,类,继承,重写

1.单继承

父类也叫基类

子类也叫派生类

如下所示,继承的关系:

对python中类的继承与方法重写介绍

继承的书写格式:


class 子类(父类):

方法

实例:


class Animal:
   def eat(self):
      print("-----吃-------")
   def drink(self):
      print("-----喝--------")
class Dog(Animal):
    def drak(self):
      print("汪汪叫")
a=Animal()
a.eat()

孙类是可以继承爷爷类的,如下所示:


class Animal:
def eat(self):
print("---吃-----")
def drink(self):
print("----喝-----")
def sleep(self):
print("----睡觉-----")
class Dog(Animal):
def bark(self):
print("---汪汪叫----")

class Xiaotq(Dog):
def fly(self):
print("----飞-----")

xiaotq = Xiaotq()
xiaotq.fly()
xiaotq.bark()
xiaotq.eat()

2.重写

子类和父类中拥有方法名相同的方法,说明子类重写了父类的方法

重写的作用:父类中已经有了这个方法,但子类想修改里面的内容,直接修改父类是不好的,就需要用到重写

例如:


class Animal:
def eat(self):
print("---吃-----")
def drink(self):
print("----喝-----")
def sleep(self):
print("----睡觉-----")
class Dog(Animal):
def bark(self):
print("---汪汪叫----")

class Xiaotq(Dog):
def fly(self):
print("----飞-----")
def bark(self):
print("----狂叫-----")

xiaotq = Xiaotq()
xiaotq.fly()
xiaotq.bark()
xiaotq.eat()

这样做,父类的方法是不会被调用的,需要用以下方式:


class Animal:
def eat(self):
print("---吃-----")
def drink(self):
print("----喝-----")
def sleep(self):
print("----睡觉-----")
class Dog(Animal):
def bark(self):
print("---汪汪叫----")

class Xiaotq(Dog):
def fly(self):
print("----飞-----")
def bark(self):
print("----狂叫-----")
#调用被重写的父类的方法
#1 必须加上self
Dog.bark(self)
#2
super().bark()

xiaotq = Xiaotq()
xiaotq.fly()
xiaotq.bark()
xiaotq.eat()

来源:https://blog.csdn.net/chenjuan0530/article/details/78480810

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com