类的继承
继承是面向对象的重要特性之一;
继承关系:继承是相对两个类而言的父子关系,子类继承了父类的所有公有属性和方法
继承实现了代码重用
使用继承:
python类名后面括号类的表示继承关系,括号中即为父类。
class Myclass(parentClass)
如果父类定义了__init__方法。子类必须显示
父类的__init__方法:
ParentClass.init(self,[args…])
如果子类需要扩展父类的行为,可以添加:
__init__方法的参数。
子类继承父类
[root@jie class_demo]# cat jicheng.py
#!/usr/bin/python
#coding:utf8
class People(object):
color = "yellow"
def __init__(self,c):
print "init ...."
self.dwell="earth"
def think(self):
self.color = "black"
print ("I am a %s" %self.color)
print "I am a thinker"
class Chinese(People):
# def __init__(self):
# People.__init__(self,'red')
#super继承方
def __init__(self):
super(Chinese,self).__init__('red')
def talk(self):
print ("我是子类方法")
def think(self):
print ("我改变了父类方法think")
pass
cn=Chinese()
print cn.color
cn.think()
print cn.dwell
cn.talk()
运行:
[root@jie class_demo]# python jicheng.py
init ....
yellow
我改变了父类方法think
earth
我是子类方法
多重继承
python 支持多重继承,及一个类可以继承多个父类:
语法:class class_name(Parent_c1,Parent_c2,…)
注意:
当父类中出现多个自定义的__init__方法时,多重继承只执行第一个类的__init__方法,其他不执行
class Chinese(Martian,People): 谁写前面就先继承谁
[root@jie class_demo]# cat Martian.py
#!/usr/bin/python
#coding:utf8
class People(object):
color = "yellow"
def __init__(self):
self.dwell="earth"
def think(self):
print ("I am a %s" %self.color)
print ("My home is %s" %self.dwell)
class Martian(object):
color = 'red'
def __init__(self):
self.dwell = "Martian"
def talk(self):
print ("Martian")
class Chinese(People,Martian):
def __init__(self):
#Martian.__init__(self)
People.__init__(self)
pass
cn=Chinese()
cn.think()
cn.talk()
运行脚本:
[root@jie class_demo]# python Martian.py
I am a yellow
My home is earth
Martian