龙空技术网

python基础知识,python类的单继承与多继承,以及继承的作用?

科技yuan 285

前言:

如今姐妹们对“python中继承的作用”大致比较注重,姐妹们都需要分析一些“python中继承的作用”的相关知识。那么小编同时在网摘上汇集了一些有关“python中继承的作用””的相关文章,希望小伙伴们能喜欢,大家一起来了解一下吧!

python类的继承

python允许在一个或多个类的基础上生成新的类,新的类可以使用父类的一些属性和方法,这个过程就叫做继承。

python继承最大的作用就是为了减少代码。

男人和女人统称为人类,都可以继承人类共同的属性,这就是继承的概念。

继承示例

继承

代码:(父类→People)

class People: def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating..."%self.name) def talk(self): print("%s is talking..."%self.name) def sleep(self): print("%s is sleeping..."%self.name)

代码:(子类→男(Man))

#写一个子类,继承父类class Man(People): #在子类中定义新的方法 def Study(self): print("%s is studying..."%self.name) #在子类中重构父类方法 def sleep(self): People.sleep(self) print("man is sleeping...")m1=Man("ZhiZhuXia",22)m1.eat()m1.Study()m1.sleep()运行结果:ZhiZhuXia is eating...ZhiZhuXia is studying...ZhiZhuXia is sleeping...man is sleeping...说明:1、可以运行父类的方法;2、可以在子类中自己定义新的方法;3、可以在子类中重构父类方法。重构父类方法的代码: People.sleep(self)

代码:(子类→女(Woman))

#女类class Woman(People): def get_birth(self): print("%s is born a baby..."%self.name)w1=Woman("Green",25)w1.get_birth()w1.Study()运行结果:AttributeError: 'Woman' object has no attribute 'Study'Green is born a baby...说明:1、在本子类中无法运行其它子类中的方法。

子类

为子类添加新的方法,而不能影响到其它子类

代码:普通子类继承

class Man(People): def __init__(self,name,age,money): People.__init__(self,name,age) self.money=money print("%s time is money======"%self.money)运行结果:1000 time is money======ZhiZhuXia is eating...ZhiZhuXia is studying...ZhiZhuXia is sleeping...man is sleeping...Green is born a baby...说明:在子类中重构方法时,需要将父类中所有参数重新编写,否则在调用时会出错,写完之后然后写自己想添加的新参数,此时的新参数与父类就无关了。重构完父类之后,想要让父类先生效,就加一个People._init_,执行完父类参数后,就执行添加的子类新参数。

另一种调用父类构造参数的方法:

super(Man,self.__init__(name,age))实现效果与People._init_(self,name,age)相同。在多继承中super的方法会比People方便很多,不需要多次书写。class Man(People,Animal): def __init__(self,name,age,money): People.__init__(self,name,age) Animal.__init__(self,name,age) # super(Man,self.__init__(name,age))
多继承

Python类分为两种,一种叫经典类,一种叫新式类。两种都支持多继承。

写法如下:

class People:#经典类

class People(object):#新式类

经典类的多继承:

# 经典类class A(): def __init__(self): print 'A'class B(A): def __init__(self): A.__init__(self) print 'B'class C(B, A): def __init__(self): A.__init__(self) B.__init__(self) print 'C'说明:采用经典类的多继承,前者在调用时需要重复调用父类A的init_()函数2次。

新式类的多继承:

class A(object): def __init__(self): print 'A'class B(A): def __init__(self): super(B, self).__init__() print 'B'class C(B, A): def __init__(self): super(C, self).__init__() print 'C'说明:采用新式类,最顶层的父类一定要继承于object,这样就可以利用super()函数来调用父类的init()等函数,每个父类都执行且执行一次,并不会出现重复调用的情况。而且在子类的实现中,不用到处写出所有的父类名字。
结语

感谢阅读,欢迎在评论区中发表自己不同的观点,若有其他问题请在评论区留言,喜欢的朋友请多多关注转发支持一下。

python3-类变量的作用及析构函数

标签: #python中继承的作用